Ecko
Ecko

Reputation: 1080

Getting return value from tkinter button when clicked

I need a tkinter Button to assign a value to a variable, but I can't figure out how. I can't just put the assignment in the button callback function, because that would be local within the callback function and would be lost. How can I get a value back from the button in my main function?

Here is the code:

def newfile():
    def create_file(entry):
        file=open(entry.get(0),'w')
        return file
    chdir(askdirectory())
    name=Tk()
    name.title("Name the File?")
    prompt=Label(name, text="Enter name for new file:")
    prompt.grid(row=0)
    e=Entry(name)
    e.grid(row=1)
    e.insert(0, "Untitled")
    create=Button(name, text="Create")
    #Code I want the button to execute: current=create_file(e), name.destroy()
    create.grid(row=2, column=3)
    name.mainloop()
    return current

Does anyone know?

Also, I need to be able to retrieve current from the return of newfile().

Upvotes: 1

Views: 1847

Answers (2)

Annonymous
Annonymous

Reputation: 978

If you use nonlocal current, you should be able to directly set the current variable within the create_file function, as long as current has already been defined, it should work. Remember to put the function call connected to the buttons command argument, in a lambda function, so you can give it the argument. In the future, though, really do follow the comments, the whole code could be reorganised to make it seem more sensible...

def newfile():
    current = None
    def create_file(entry):
        nonlocal current
        current = open(entry.get(),'w')
        e.master.destroy()
    chdir(askdirectory())
    name=Tk()
    name.title("Name the File?")
    prompt=Label(name, text="Enter name for new file:")
    prompt.grid(row=0)
    e=Entry(name)
    e.grid(row=1)
    e.insert(0, "Untitled")
    create=Button(name, text="Create", command = lambda: create_file(e))
    create.grid(row=2, column=3)
    name.mainloop()
    return current

Upvotes: 1

Eric Levieil
Eric Levieil

Reputation: 3574

What I would do is create a class, in this class define name and current as class variables (self.name and self.current) so I could modify them in a class function without problem.

Upvotes: 0

Related Questions