1

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.

1
  • The time between the creation of the Button, and the line after that where you assign filepath, is about a thousandth of a second. The user would have to have very fast reflexes to navigate through the open file dialog in that small window of opportunity :-) I'm oversimplifying somewhat, but the point of my joke is, don't rely on user input being present at any line before mainloop. Commented Oct 9, 2013 at 19:58

1 Answer 1

2

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())
Sign up to request clarification or add additional context in comments.

1 Comment

Hey Kevin, thanks. I get what I am doing wrong, however, assigning filepath after the mainloop doesn't help.. if I just print filepath before the return it doesn't print it. I have the feeling the program doesn't leave open_file_dialog() at all ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.