当 Main Window 不可见时隐藏或关闭 Tkinter Top Level Window

Hide or Close Tkinter Top Level Window When Main Window Is Not Visible

如果主 window 不可见,是否有关闭或最好隐藏顶层 window 的方法。我已经能够通过检查是否已单击最小化按钮来做到这一点,但是有几种方法可以“最小化”window,例如进入另一个选项卡点击任务栏的右侧(或左侧)取决于您的系统语言)等...谢谢!

您可以尝试将函数绑定到 window 的 <Unmap><Map> 事件。如下所示:

from tkinter import *


root = Tk()
root.geometry("600x300")
for _ in range(3):
    Toplevel(root)

def hide_all(event):
    # You could also call each child directly if you have the object but since we aren't tracking
    # the toplevels we need to loop throught the children
    for child in root.children.values():
        if isinstance(child, Toplevel):
            child.withdraw() # or depending on the os: 'child.wm_withdraw()'

def show_all(event):
    # You could also call each child directly if you have the object but since we aren't tracking
    # the toplevels we need to loop throught the children
    for child in root.children.values():
        if isinstance(child, Toplevel):
            child.deiconify() # or depending on the os: 'child.wm_deiconify()'

root.bind("<Unmap>", hide_all) # Fires whenever 'root' is minimzed
root.bind("<Map>", show_all) # Fires whenever 'root' is restored and shown
root.mainloop()

如果这不是您想要的,您可以使用 <Expose><Visibility> 事件来获得您想要的。 Link 所有 tkinter 事件:tkinter events from anzeljg