Skip to content Skip to sidebar Skip to footer

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 wi

Solution 1:

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

Solution 2:

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.

Post a Comment for "Getting Return Value From Tkinter Button When Clicked"