【问题标题】:How to detect if my Tkinter windows has focus?如何检测我的 Tkinter 窗口是否有焦点?
【发布时间】:2020-10-18 03:44:01
【问题描述】:

我正在制作一个 tkinter 应用程序,我需要知道我的窗口是否有焦点,因为只有当窗口没有焦点时我才会发送通知。我检查了根协议,但没有找到合适的。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    这个问题已经被回答了,但是接受的答案比它应该的要复杂。

    我认为这个问题最干净的解决方案如下:

    def has_focus(window):
            return window.focus_displayof()    # returns None if the window does not have focus
    
    if not has_focus(root):
        # do something
    

    【讨论】:

    • 很好的答案,但不需要函数,可以简单地使用if not root.focus_displayof()
    • @Saad,创建一个函数当然是可选的,但它大大提高了可读性。
    【解决方案2】:

    可以有多种方法来执行此操作,具体取决于您要触发的功能。

    假设您希望在窗口失去焦点时发出通知,然后在<FocusOut>bind 的帮助下我们可以这样做

    ...
    
    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))
    

    【讨论】:

      【解决方案3】:

      我发现a StackOverflow question 看起来和你的很相似。本质上,您需要为您的 Tkinter 应用程序添加绑定。这仅在您的应用程序具有焦点时才起作用。如果将对象应用到根对象,还可以使用 focus_get 命令确定对象是否具有焦点。

      这是 2009 年答案使用的代码:e1.bind("&lt;Return&gt;", handleReturn)

      【讨论】:

      • 这是工作,但这不是最好的方法,还是谢谢你:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多