2

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?

Another_coder
  • 728
  • 1
  • 9
  • 23
  • I know that in vanilla tkinter you can use `.winfo_exists()` to check if a widget exists or not, which also works on instances of `tkinter.Toplevel`. You might give that a try! – JRiggles Feb 09 '23 at 19:54
  • Wouldn't that mean I have to run some kind of timer to constantly check if the window exists? That seems quite clunky :( – Another_coder Feb 09 '23 at 19:57
  • Potentially, but that depends on what you're actually trying to accomplish. If you just want to call a function, i.e. do something when the window is closed, this is pretty trivial to implement. And periodic timers in tkinter aren't too hard to deal with either thanks to the `after()` method – JRiggles Feb 09 '23 at 20:04

1 Answers1

3

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.

CodeCop
  • 1
  • 2
  • 15
  • 37