如何处理,当Tkinter的窗口获得焦点
问题描述:
我有这样的代码:如何处理,当Tkinter的窗口获得焦点
from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()
它打印hello world
只有一次,然后停止工作。没有更多hello world
基本上WM_TAKE_FOCUS
不起作用。
答
您可以将函数绑定到<FocusIn>
事件。绑定到根窗口时,绑定会应用到根窗口中的每个窗口小部件,因此如果您只想在窗口整体获得焦点时执行某些操作,则需要将event.widget
与根窗口进行比较。
例如:
import Tkinter as tk
def handle_focus(event):
if event.widget == root:
print("I have gained the focus")
root = tk.Tk()
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
entry1.pack()
entry2.pack()
root.bind("<FocusIn>", handle_focus)
root.mainloop()
答
“请注意,不推荐使用WM_SAVE_YOURSELF,并且Tk应用程序无法正确实现WM_TAKE_FOCUS或_NET_WM_PING,所以WM_DELETE_WINDOW是唯一应该使用的”。 Here's a link! 如果你需要保持Tkinter的集中所有的时间:
w.wm_attributes("-topmost", 1)
做了很好的工作。
我需要做一些事情,当窗口获得焦点。 –