How to Close Child Window in Tkinter

How to detect if a child window is opened or closed in tkinter

You can create a reference to if the window is closed or not, then continue, like:

opened = False # Create a flag
# First Window
def open_first_win():
global opened
if not opened:
first_win = Toplevel(root)
first_win.title("First Window")
opened = True # Now it is open
first_win.protocol('WM_DELETE_WINDOW',lambda: onclose(first_win)) # If it is closed then set it to False

def onclose(win): # Func to be called when window is closing, passing the window name
global opened
opened = False # Set it to close
win.destroy() # Destroy the window

# Second Window
def open_second_win():
global opened
if not opened:
second_win = Toplevel(root)
second_win.title("Second Window")
opened = True
second_win.protocol('WM_DELETE_WINDOW',lambda: onclose(second_win))

As the word stands, protocol just adds some rules to the windows, like WM_DELETE_WINDOW means what function to call, when the window is tried to close.

Why does closing a tkinter child window with `frame.quit` exit my application?

It is because quit causes mainloop to exit. With no event loop running, there's nothing left to keep the main window alive.

If you want to close a child window, call the destroy method.

self.close_button = tk.Button(..., command=self.top.destroy)


Related Topics



Leave a reply



Submit