Check if window is in background Tkinter

≡放荡痞女 提交于 2021-02-05 09:20:10

问题


So, I'm trying to make an app on tkinter. I've just started learning how this module works.

In my app, I have a root window and a child (top leveled) window, and I set the child to be always on top. When I minimize my root window, the child window also minimizes, because I have defined that condition. My problem is when I select other window. When I do it, the child window still stays on top and I want to know if there is a way to know if my root window is in background, a.k.a.: I'm not currently working on it (like a root.winfo_... function).

I can provide other examples as I feel that I am not explaining my problem in a way that you understand. I can also provide my code but I think that is now necessary.


回答1:


Question: Check if window is in background

Using tk.self.winfo_containing(... you can determine if a widget, here the root window, is shown at Top Level. In this example, the center of the given window is used as visible point.

Note: While you move the window, the result may be False.


Reference: - 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()

Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6 - Linux
Note: Confirmed, works on Windows.
May not work on MACOS.



来源:https://stackoverflow.com/questions/60442386/check-if-window-is-in-background-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!