I'm having trouble returning a variable from a tkinter Button command. Here is my code:
class trip_calculator:
def __init__(self):
file = self.gui()
def gui(self):
returned_values = {}
def open_file_dialog():
returned_values['filename'] = askopenfilename()
root = Tk()
Button(root, text='Browse', command= open_file_dialog).pack()
filepath = returned_values.get('filename')
root.mainloop()
return filepath
root.quit()
I just want to return the filepath of a text file. The tkinter window is open and I can browse and choose the file but it then doesn't return the path.
The way your code is now, filepath is assigned its value before your window even appears to the user. So there's no way the dictionary could contain the filename that the user eventually selects. The easiest fix is to put filepath = returned_values.get('filename') after mainloop, so it won't be assigned until mainloop ends when the user closes the window.
from Tkinter import *
from tkFileDialog import *
class trip_calculator:
def gui(self):
returned_values = {}
def open_file_dialog():
returned_values['filename'] = askopenfilename()
root = Tk()
Button(root, text='Browse', command= open_file_dialog).pack()
root.mainloop()
filepath = returned_values.get('filename')
return filepath
root.quit()
print(trip_calculator().gui())
Related
I'm new to Tkinter and I'm trying to create a simple Button that opens a file dialog box, where the user chooses which CSV file to open. Under the button there is a label that should display the file path for the file that was opened.
When I click on the button once, everything works as expected. However, if I click on it a second time and select a different file, the new filepath overlaps with the previous one, instead of replacing it.
Here is the code for the implementation function (please let me know if you need more bits of code for context):
def open_csv_file():
global df
global filename
global initialdir
initialdir = r"C:\Users\stefa\Documents\final project models\Case A"
filename = filedialog.askopenfilename(initialdir=initialdir,
title='Select a file', filetypes = (("CSV files","*.csv"),("All files","*.*")))
df = pd.read_csv(os.path.join(initialdir,filename))
lbl_ok = tk.Label(tab2, text = ' ') #tab2 is a ttk.Notebook tab
lbl_ok.config(text='Opened file: ' + filename)
lbl_ok.grid(row=0,column=1)
Here is how to do it with .config(), create the label instance just once (can then grid as much as you want but probably just do that once too), then just configure the text:
from tkinter import Tk, Button, Label, filedialog
def open_file():
filename = filedialog.askopenfilename()
lbl.config(text=f'Opened file: {filename}')
root = Tk()
Button(root, text='Open File', command=open_file).grid()
lbl = Label(root)
lbl.grid()
root.mainloop()
You can use a StringVar for this. Here is an example that may help you:
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.geometry('200x200')
def openCsv():
csvPath.set(askopenfilename())
csvPath = StringVar()
entry = Entry(root, text=csvPath)
entry.grid(column=0, row=0)
btnOpen = Button(root, text='Browse Folder', command=openCsv)
btnOpen.grid(column=1, row=0)
root.mainloop()
Hi I am pretty new to tkinter and have being trying to create a button that opens a window then a have a button in the new window the gives a message when pressed. I ran into the problem that the only whay I could get it to recognise the function I wrote was to write it inside the function that opens the second window. I don't know if I have being searching for the wrong things but I can't find how to do this properly. Can someone help me out Here is my code
from tkinter import *
master = Tk()
master.title("frame control")
def win():
window2 = Toplevel()
def open():
stamp = Label(window2, text="Staped").pack()
lab2 = Button(window2,text = "yo ",command = open).pack()
lab1 = Button(master,text = " open a new window" , command = win).pack()
mainloop()
This is your code but with best practises:
import tkinter as tk
def create_stamp():
stamp = tk.Label(window2, text="Stamp")
stamp.pack()
def create_second_win():
global window2
window2 = tk.Toplevel(root)
lab2 = tk.Button(window2, text="Click me", command=create_stamp)
lab2.pack()
root = tk.Tk()
root.title("Frame control")
button = tk.Button(root, text="Open a new window", command=create_second_win)
button.pack()
root.mainloop()
I made window2 a global variable so that I can access it from create_stamp. Generally it is discouraged to use from ... import *. As #Matiiss said, sometimes you can have problems with global variables if you don't keep track of the variable names that you used.
If you want to avoid using global variables and want to use classes, look at this:
import tkinter as tk
class App:
def __init__(self):
self.stamps = []
self.root = tk.Tk()
self.root.title("Frame control")
self.button = tk.Button(self.root, text="Open a new window", command=self.create_second_win)
self.button.pack()
def create_stamp(self):
stamp = tk.Label(self.window2, text="Stamp")
stamp.pack()
self.stamps.append(stamp)
def create_second_win(self):
self.window2 = tk.Toplevel(self.root)
self.lab2 = tk.Button(self.window2, text="Click me", command=self.create_stamp)
self.lab2.pack()
def mainloop(self):
self.root.mainloop()
if __name__ == "__main__":
app = App()
app.mainloop()
As #Matiiss mentioned it would be more organised if you move the second window to its own class. For bigger projects it is a must but in this case you don't have to.
I'm just starting to use tkinter and it is a little difficult to handle it. Check this sample :
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import Tkinter as tk
import tkFileDialog
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
I juste created a browse button which keep the file path in the variable "filename" in the function openfile(). How can i put the content of "filename" in a variable out of the function ?
For example I want to put it in the variable P and print it in a terminal
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
P = "the file path in filename"
print P
I also also want to put the file path in a widget Entry(), and as same as below, get the text in the Entry widget in another global variable.
If someone knows, it would be nice.
There are at least two different ways of doing it:
1) Bundle your whole app in a class like this:
import Tkinter as tk
import tkFileDialog
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self) # create window
self.filename = "" # variable to store filename
tk.Button(self, text='Browse', command=self.openfile).pack()
tk.Button(self, text='Print filename', command=self.printfile).pack()
self.spinbox = tk.Spinbox(self, from_=0, to=10)
self.spinbox.pack(pady=10)
tk.Button(self, text='Print spinbox value', command=self.printspinbox).pack()
self.mainloop()
def printspinbox(self):
print(self.spinbox.get())
def openfile(self):
self.filename = tkFileDialog.askopenfilename(title="Open file")
def printfile(self):
print(self.filename)
if __name__ == '__main__':
App()
In this case, filename is an attribute of the App, so it is accessible from any function inside the class.
2) Use a global variable:
import Tkinter as tk
import tkFileDialog
def openfile():
global filename
filename = tkFileDialog.askopenfilename(title="Open file")
def printfile():
print(filename)
def printspinbox():
print(spinbox.get())
window = tk.Tk()
filename = "" # global variable
tk.Button(window, text='Browse', command=openfile).pack()
tk.Button(window, text='Print filename', command=printfile).pack()
spinbox = tk.Spinbox(window, from_=0, to=10)
spinbox.pack(pady=10)
tk.Button(window, text='Print spinbox value', command=printspinbox).pack()
window.mainloop()
I'm trying to use Tkinter and get the user to choose a certain file. My code looks like this (I'm just starting out with Tkinter)
from Tkinter import *
from tkFileDialog import *
root = Tk()
root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.")
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()
root.mainloop()
When I run the program, I get an error that says:
NameError: name 'tkFileDialog' is not defined
I've tried it with a few configurations I found online. None of them have worked; but this is the same basic error every time. How can I fix this?
You are importing everything from tkFileDialog module, so you don't need to write a module-name prefixed tkFileDialog.askopenfilename(), just askopenfilename(), like:
from Tkinter import *
from tkFileDialog import *
root = Tk()
root.wm_title("Pages to PDF")
w = Label(root, text="Please choose a .pages file to convert.")
fileName = askopenfilename(parent=root)
w.pack()
root.mainloop()
Try this:
from Tkinter import *
import tkFileDialog
root = Tk()
root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.")
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()
root.mainloop()
Seems a space name problem.
Try this:
try:
import Tkinter as tk
import tkFileDialog as fd
except:
import tkinter as tk
from tkinter import filedialog as fd
def NewFile():
print("New File!")
def OpenFile():
name = fd.askopenfilename()
print(name)
def About():
print("This is a simple example of a menu")
class myGUI:
def __init__(self, root):
self.root = root
self.canvas = tk.Canvas(self.root,
borderwidth=1,
relief="sunken")
self.canvas.pack( fill=tk.BOTH, expand=tk.YES)
self.menu = tk.Menu(self.root)
self.root.config(menu=self.menu)
self.helpmenu = tk.Menu(self.menu)
self.filemenu = tk.Menu( self.menu )
self.menu.add_cascade(label="File", menu=self.filemenu)
self.filemenu.add_command(label="New", command=NewFile)
self.filemenu.add_command(label="Open...", command=OpenFile)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=root.destroy)
root = tk.Tk()
root.title('appName')
myGUI(root)
root.mainloop()
This is my main file:
ExcelAppl = win32com.client.Dispatch('Excel.Application')
Workbook = ExcelAppl.Workbooks.Open('excel file path')
Sheet = Workbook.Worksheets.Item(1)
This is the Python GUI:
root = Tk()
def callback():
file_path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
print "the file path %s",file_path
Text_button.insert(INSERT,file_path)
def execute():
execfile("MainLibrary.py")
Browse_button = Button(text='Browse', command=callback).pack(side=LEFT, padx=10, pady=20, ipadx=20, ipady=10)
Execution_button = Button(text='Convert', command=execute).pack(side=BOTTOM, padx=10, pady=20, ipadx=20, ipady=10)
root.mainloop()
This is my query. I need to get the file_path from the GUI and assign it to Workbook = ExcelAppl.Workbooks.Open('excel file path'). I need to get the path from the GUI and assign the path to my main code. Can anyone help?
You don't need execfile() here.
You could define a function in main_library.py instead:
import win32com.client
def do_something_with_excel_file(filename):
app = win32com.client.Dispatch('Excel.Application')
workbook = app.Workbooks.Open(filename)
worksheet = workbook.Worksheets.Item(1)
# use `worksheet` ...
if __name__=="__main__":
import sys
# get filename from command-line if called as a script
do_something_with_excel_file(sys.argv[1])
Then you could import it in your GUI code:
import tkFileDialog
from Tkinter import as tk
import main_library
def browse():
path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
file_path.set(path)
print "the file path %s", path
def convert():
root.destroy() # quit gui
main_library.do_something_with_excel_file(file_path.get())
root = tk.Tk()
file_path = tk.StringVar()
tk.Label(root, textvariable=file_path).pack()
tk.Button(text='Browse', command=browse).pack()
tk.Button(text='Convert', command=convert).pack()
root.mainloop()