如何检测 child window 在 tkinter 中是打开还是关闭

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

我正在 Python 使用 tkinter 进行一些基本的 GUI 编程。我有一个主 window,它有两个按钮。这些按钮中的每一个都会打开一个特定的 child window,但问题是每次我单击其中一个按钮时都会生成新的 windows。我想检查 child window 是否已经打开,并防止在单击按钮时多次打开相同的 window。如何检查 child window 是打开还是关闭?

我阅读了文档和 Whosebug 上的一些帖子,但找不到相关的解决方案。

我的代码简介:

# 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()

如果window是否关闭,你可以创建一个引用,然后继续,比如:

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))

顾名思义,protocol 只是在 windows 上添加了一些规则,比如 WM_DELETE_WINDOW 表示当 window 试图关闭时要调用的函数.