Search code examples
pythontkintertoplevel

Binding closing of toplevel window


How can I create a binding in tkinter for when someone closes a toplevel window or if it is closed with toplevel1.destroy() or something similar. I am trying to make a small pop-up and when the user closes the main window or toplevel I want to prompt the user to save a file. I have figured out that I can set the actual close button to the function but cannot figure out how to get .destroy() and the closing of the main window to call the function. What should I do to bind the destroy function or window closing function?

Tested code:

import tkinter as tk
class TestWidget(tk.toplevel):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(*args, **kwargs)
        self.protocol("WM_DELETE_WINDOW", self.close)

    def close(self):
        print("Closed")
        self.destroy()

if __name__ == "__main__":
    root = tk.Tk()
    TestWidget()
    root.mainloop()

Solution

  • So I figured out that if you make a toplevel widget integrated into a class that you can find all the classes with the code below:

    for child in root.winfo_children():
            print(child)
    

    This returns all the widgets and classes used:

    .!testwidget
    .!testwidget2
    

    With this I can set up a function in the main window to call the child's close function one by one and this allows me to gain access to all the needed pieces