Reputation: 1390
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.
Upvotes: 1
Views: 4843
Reputation: 76184
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())
Upvotes: 2