Search code examples
pythonuser-interfacetkinterdestroy

Python TKInter destroy not working


I am trying to close a TKInter window with self.win.destroy.

The following error is thrown when binding the event to a button:

...
Can't invoke "bind" command: application has been destroyed
During handling the above exception, another exception occured:
...
Can't invoke "destroy" command: application has been destroyed

How do I bind a "close-window" command to the button?


Solution

  • Do this:

    button['command'] = root_window.destroy # give it the function
    # when the button is pressed the call () is done
    

    Do not do this:

    button.bind('<Button-1>', root_window.destroy()) # () makes the call
    

    because

    root_window.destroy()
    

    destroys the window before button.bind is called.

    This is also wrong: but does not destroy the root window:

    button.bind('<Button-1>', root_window.destroy)
    

    because

    • the button can not be triggered with the keyboard
    • root_window.destroy(event) is called but root.destroy() only takes one argument.

    This does also work:

    button.bind('<Button-1>', lambda event: root_window.destroy())