Search code examples
pythontkinterwindow

Is there any way of doing something after the Tkinter window is closed?


So I have this program which runs inside a tkinter window. The idea is that when a user finishes using the porgram their scores/info from that session is stored, so their scores should only be stored after they shut the window down.

I am wondering if there is anything which could tell the program when the user presses the close button (from the window, not an in-window widget) so that processes only happen after they close the window.


Solution

  • The mainloop function only ends once the root window is closed, so you can just put your code after that.

    from Tkinter import *
    
    root = Tk()
    root.mainloop()
    print("This message should appear after the window closes.")
    

    I suppose you could also register a protocol handler to catch WM_DELETE_WINDOW events, but that seems like an unnecessary complication.

    from Tkinter import *
    
    def x_button_pressed():
        print("This message should appear after the window closes.")
        root.destroy()
    
    root = Tk()
    root.protocol("WM_DELETE_WINDOW", x_button_pressed)
    root.mainloop()