检查 window 是否在后台 Tkinter

Check if window is in background Tkinter

所以,我正在尝试在 tkinter 上制作一个应用程序。我刚刚开始学习这个模块的工作原理。

在我的应用程序中,我有一个根 window 和一个 child(顶级)window,并且我将 child 设置为始终在顶部。当我最小化根 window 时,child window 也会最小化,因为我已经定义了那个条件。我的问题是当我 select 其他 window。当我这样做时,child window 仍然保持在顶部,我想知道是否有办法知道我的根 window 是否在后台,a.k.a。 : 我目前没有在处理它(比如 root.winfo_... 函数)。

我可以提供其他示例,因为我觉得我没有以您理解的方式解释我的问题。 我也可以提供我的代码,但我认为现在有必要。

Question: Check if window is in background

使用 tk.self.winfo_containing(... 您可以确定小部件(此处为 root window)是否显示在 顶级 。 在此示例中,给定 window 的中心用作 visible 点。

注意:当你移动window时,结果可能是False


参考: - Tkinter.Widget.winfo_containing-method

Returns the widget at the given position, or None


import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.is_toplevel()

    def is_toplevel(self):
        width, height, x, y = self.winfo_width(), self.winfo_height(), \
                              self.winfo_rootx(), self.winfo_rooty()

        if (width, height, x, y) != (1, 1, 0, 0):
            is_toplevel = self.winfo_containing(x + (width // 2),
                                                y + (height // 2)
                                                ) is not None

            print('is_toplevel: {}'.format(is_toplevel))

        self.after(2000, self.is_toplevel)


if __name__ == "__main__":
    App().mainloop()

测试 Python:3.5 - 'TclVersion':8.6 'TkVersion':8.6 - Linux
注意:已确认,适用于 Windows
可能不适用于 MACOS.