python - Tk/Tkinter : Detect application lost focus

标签 python tkinter tk-toolkit

我正在制作一个 Tkinter 应用程序。在应用程序中,我想弹出一个上下文菜单,我使用 Tk.Menu.post() 来实现。

我不知道如何在应用程序失去焦点时使此菜单消失。我需要这样做,因为即使切换到另一个窗口,菜单仍保留在顶部,留下菜单'神器'。

我放了一个<FocusOut>菜单上的事件,如果菜单具有焦点并且用户将焦点移动到另一个应用程序,则会触发该事件。这效果很好。

如果主应用程序窗口获得焦点,我该怎么办?我可以输入 <FocusOut>应用程序窗口上的事件,关闭菜单;但是,当我将焦点放在菜单上并关闭菜单时,这最终会被调用。菜单是用父应用程序作为主应用程序创建的,所以我不确定为什么<FocusOut>当菜单获得焦点时,主应用程序上的事件甚至会被触发。

如何区分主应用程序窗口失去焦点到其他应用程序与失去焦点到我的菜单?

我不想使用 tk_popup() 因为我希望用户继续向主窗口提供输入。 (菜单的使用是可选的)。

感谢@Brad Lanam,我想出了一个解决方案,我已将其包括在内:

from Tkinter import *

class App(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        self.entry = Entry(self)
        self.entry.grid(padx=30, pady=30)
        self.entry.focus_set()
        self.entry.bind("<Tab>", self.put_menu)
        self.entry.bind("<Down>", self.set_focus_on_menu)

        self.menu = Menu(self, tearoff=False)
        self.menu.add_command(label="test")
        self.menu.bind("<FocusOut>", self.destroy_menu)


        self.bind("<FocusIn>", self.app_got_focus)
        self.bind("<FocusOut>", self.app_lost_focus)
        self.bind("<3>", self.put_menu)


    def app_got_focus(self, event):
        self.config(background="red")

    def app_lost_focus(self, event):
        self.config(background="grey")

        ######## SOLUTION BEGIN #########
        if self.focus_get() != self.menu:
            self.destroy_menu(event)
        ######## SOLUTION END ###########

    def set_focus_on_menu(self, event):
        self.menu.focus_set()

    def menu_got_focus(self, event):
        self.menu.activate(0)

    def put_menu(self, event):
        self.menu.post(self.winfo_x() + self.entry.winfo_x(), self.winfo_y() + self.entry.winfo_y()+20)

    def destroy_menu(self, event):
        self.menu.destroy()

app = App()

app.mainloop()

最佳答案

self.focus_get() 将返回具有焦点的对象,该对象可用于区分接收焦点的菜单与其他应用程序。

例如,当焦点移动到另一个应用程序时删除菜单:

def app_lost_focus(self, event):
    if self.focus_get() != self.menu:
        self.destroy_menu(event)
    

关于python - Tk/Tkinter : Detect application lost focus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18089068/

相关文章:

python - 我在代码底部附近收到一个列表不可调用错误,其中显示 ball.append,但我不知道如何修复它

python - Matplotlib 和多处理 RuntimeError

Python Tkinter Tk root.after 延迟

python - Beautifulsoup 使用页面源代码片段创建 Soup

python - 对列的部分函数进行 Pandas 矢量化

python - 替代 sklearn.model_selection import GridSearchCV

python - 为什么python模块newspaper3k只返回腾讯、新浪和wallstreetcn的0篇文章?

python - 为什么这个图像在 tkinter 中不显示?

python - "tkinter TclError: bad file type"使用 askopenfilename

Python 3.3 tkinter.filedialog.askopenfile() 留下无响应的 Tk 窗口