0

I am a absolutly beginner in Tkinter and I need already help: I wanted to open a file with a button. I found everywhere this very simple example:

from Tkinter import *
from tkFileDialog   import askopenfilename      

def callback():
    name= askopenfilename() 
    print name

errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()

But how can I call now the variable "name" from the function callback? I need this variable outside of this function! Of course, I can also open the file also in the callback function, but I need the opened file to save the content in an array and work with the array...

2
  • You can make this variable global. Commented Mar 18, 2015 at 20:30
  • ... but even if you do make it global it will not help much to use it outside of the function before the function is being called! Why not do the file handling in the callback function? I think you should read up on classes in Tkinter and create a custom Frame and make that variable a member of that frame. Commented Mar 18, 2015 at 20:31

2 Answers 2

6

The best approach would be to make callback a method in a class:

class Asker(object):
    def __init__(self):
        self.name = None
    def callback(self):
        self.name = askopenfilename() 
        print self.name

ask = Asker()
Button(text='File Open', command=ask.callback).pack(fill=X)

Now, object ask persists, and ask.name is None if the callback has not executed yet, and after it has, the result of askopenfilename.

You could use a global instead but there's really no advantage in so doing so I recommend you use this class-based approach.

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

4 Comments

The OP is completely a beginner. I am not sure if this is the best approach for him.
@Rinzler, if the class approach introduced complications I might agree, but it really doesn't -- no need for the poor beginner to suffer through the complications that the use of global is likely to run into.
I understand that in this case the class-based approach is easier, but it might not even know what a class is ;)
@Rinzler, it doesn't matter -- the OP might not know what a class is nor what a global is, but he or she needs one or the other, so let's suggest the simpler and superior one.
0

If you need some variable outside a function you need a global variable

name="" # if you don't call the function it'll remain empty!
def callback():
    global name
    name= askopenfilename() 
    print name

Comments

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.