1

I have just now begun with GUI programming in Python 2.7 with Tkinter.

I want to have a button Browse, which when clicked opens the Windows File Explorer and returns the path of file selected to a variable. I wish to use that path later.

I am following the code given here. It outputs a window displaying 5 buttons, but the buttons do nothing. On clicking the first button, it doesn't open the selected file.

Likewise, on clicking the second button, the askopenfilename(self) function is called and it should return a filename. Like I mentioned, I need that filename later.

How to I get the value returned by the function into some variable for future use?

1 Answer 1

1

There is no point in using return inside a callback to a button. It won't return to anywhere. The way to make a callback save data is to store it in a global variable, or an instance variable if you use classes.

def fetchpath():
    global filename
    filename = tkFileDialog.askopenfilename(initialdir = 'E:')

FWIW (and unrelated to the question): you're making a very common mistake. In python, when you do foo=bar().baz(), foo takes the value in baz(). Thus, when you do this:

button = Button(...).pack()

button will take the value of pack() which always returns None. You should separate widget creation from widget layout if you expect to save an actual reference to the widget being created. Even if you're not, it's a good practice to separate the two.

Sign up to request clarification or add additional context in comments.

3 Comments

I corrected the pack mistake. I am still not able to use global filename NameError: global name 'filename' is not defined
@Nancy: You must have other bugs in your program. You shouldn't get that error, but without seeing the code I can't even guess.
My mistake.Got it figured out now.

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.