pythonpython-3.xuser-interfacetkinterchildwindow

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


I am doing some basic GUI programming in Python using tkinter. I have a main window which has two buttons. Each of these buttons open a specific child window but the problem is that the new windows are generated every time I click either of the buttons. I want to check if a child window is already open and prevent opening of the same window multiple times when button is clicked. How do I check if the child window is opened or closed?

I read the documentation and some posts on stackoverflow but could not find a relevant solution.

My code brief:

# First Window
def open_first_win():
    first_win = Toplevel(root)
    first_win.title("First Window")
    
# Second Window
def open_second_win():
    second_win = Toplevel(root)
    second_win.title("Second Window")

# Main Window
root = Tk()
root.title("Main Window")
root.geometry('300x100')

btn1 = Button(root,text="Btn1",command=open_first_win)
btn1.pack()

btn2 = Button(root,text="Btn2",command=open_second_win)
btn2.pack()

root.mainloop()


Solution

  • 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.