pythontkinterdestroy

Tkinter button command activates when program is run


Found a similar thread here: Tkinter button command activates upon running program?

However I couldn't fully understand the answer being a relatively new.

def Destroy(var):
    var.destroy()

Is the function I wish too call.

exit_button = tk.Button(master, text = "Exit", command = Destroy(master))

However when I run the program, it instantly closes with the error message:

_tkinter.TclError: can't invoke "button" command:  application has been destroyed

What I want is for the program to exit once the button is pressed, and I will be using the same function to destroy other widgets etc so it needs to be a function.

Will clarify more if needed.


Solution

  • When you define exit_button you're actually calling Destroy so you need to pass a function or lambda to prevent passing a function call.

    exit_button = tk.Button(master, text = "Exit", command = lambda: Destroy(master))