1

So, I'm having some trouble to understand how I can access the value of a variable of a function from another function within a class.

    import Tkinter as tk, tkFileDialog

    class test:
        def __init__(self):
            root = tk.Tk()
            song_button = tk.Button(root, text = 'Select Song', fg = 'blue', command = self.loadfile).pack()
            #how do I access the value of filename now?

        def loadfile(self):
            filename = tkFileDialog.askopenfilename(filetypes=[("allfiles","*"),("pythonfiles","*.py")])
1
  • You want to access filename in the initializer? That'll be called before loadfile() can ever be called.. Commented Sep 3, 2012 at 19:40

1 Answer 1

1

Right now filename is just a local variable in the loadfile function. You need to make filename an attribute of the object. Do self.filename = ..., then in other methods you can access it as self.filename.

(In this particular case what you're asking seems a bit odd, since loadfile won't have been called at the time you seem to want to access filename, so filename won't even exist. But this is the general idea. No matter what, you obviously need to call the function where the variable is defined before you can do anything with it.)

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

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.