Python TkInter Button Command Return
Question: I'm having trouble returning a variable from a TkInter button command. This
here is my code:

    
    
    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()
    
            filepath = returned_values.get('filename')
    
            root.mainloop()
    
            return filepath
    
            root.quit()
    

I just want to return the filepath of a TXT file. The TkInter window is open
and I can browse and choose the file but it then doesn't return the path. I'm
going nuts!

    
    
        def __init__(self):
    
            file = self.gui()
    

Any ideas? Thanks a bunch!


Answer: 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())
    

