首页 > 解决方案 > 当主窗口不可见时隐藏或关闭 Tkinter 顶级窗口

问题描述

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

标签: pythontkintertoplevel

解决方案


您可以尝试将函数<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>or<Visibility>事件来获得您想要的。链接到所有 tkinter 事件:来自 anzeljg 的 tkinter 事件


推荐阅读