check if Toplevel windows was closed?

Question:

I have a tkinter app, created with customtkinter:

import customtkinter

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        Extra()

        self.mainloop()

class Extra(customtkinter.CTkToplevel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry("400x300")

        self.label = customtkinter.CTkLabel(self, text="ToplevelWindow")
        self.label.pack(padx=20, pady=20)

App() 

I am trying to figure out code that checks if the Extra window has been closed. I’ve been looking around and cannot seem to find anything useful. Is there a way of doing this?

Asked By: Another_coder

||

Answers:

Based on answers in this thread How do I handle the window close event in Tkinter?:

If a WM_DELETE_WINDOW message arrives when you haven’t defined a handler, then Tk handles the message by destroying the window for which it was received.

We could add a protocol named WM_DELETE_WINDOW and use the self.destroy() method as such:

class Extra(customtkinter.CTkToplevel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry("400x300")
        self.label = customtkinter.CTkLabel(self, text="ToplevelWindow")
        self.label.pack(padx=20, pady=20)

        self.protocol("WM_DELETE_WINDOW", self.closed) # <-- adding the protocol

    def closed(self):
        print("I've been closed!")
        self.destroy()

enter image description here


Resulting in:

I've been closed!

And we then terminate the extra window.

Answered By: no_hex
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.