Skip to content Skip to sidebar Skip to footer

Tkinter Button Command Return Value?

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)

Solution 1:

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

Post a Comment for "Tkinter Button Command Return Value?"