我正在制作一个tkinter应用程序,我需要知道我的窗口是否有焦点,因为我只会在窗口没有焦点时发送通知。我检查了根协议,但找不到合适的东西。
答案 0 :(得分:1)
可以使用多种方法来执行此操作,具体取决于您要触发什么功能。
假设您希望通知在窗口失去焦点时发送,然后借助<FocusOut>
绑定我们可以做到这一点
...
def send_notification(*args):
"""triggers when the window loses focus."""
...
root = tk.Tk()
root.bind('<FocusOut>', send_notification)
...
或者让我们通知功能触发不同的时间,即使窗口是否具有焦点,我们也可以像这样签入功能
def send_notification(*args):
"""triggers when the window loses focus."""
if not focus_check.get():
...
root = tk.Tk()
focus_check = tk.BooleanVar()
root.bind('<FocusIn>', lambda _: focus_check.set(True))
root.bind('<FocusOut>', lambda _: focus_check.set(False))
答案 1 :(得分:0)
我发现a StackOverflow question与您的看起来很相似。本质上,您需要向Tkinter应用程序添加绑定。仅当您的应用程序具有焦点时,此功能才起作用。如果将对象应用于根对象,也可以使用focus_get命令确定对象是否具有焦点。
以下是2009年答案使用的代码:e1.bind("<Return>", handleReturn)
答案 2 :(得分:0)
这个问题已经回答了,但是被接受的答案比应该的要复杂得多。
我认为,解决此问题的最佳方法是:
def has_focus(window):
return window.focus_displayof() # returns None if the window does not have focus
if not has_focus(root):
# do something