当 tkinter window 获得焦点时如何处理
How to handle, when tkinter window gets focus
我有这个代码:
from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()
它只打印一次hello world
,然后就停止工作了。没有了hello world
基本上WM_TAKE_FOCUS
不行
"Note that WM_SAVE_YOURSELF is deprecated, and Tk apps can't implement WM_TAKE_FOCUS or _NET_WM_PING correctly, so WM_DELETE_WINDOW is the only one that should be used"。
这里是a link!
如果您需要始终保持 tkinter 焦点:
w.wm_attributes("-topmost", 1)
做得很好。
您可以将函数绑定到 <FocusIn>
事件。当您绑定到根 window 时,绑定将应用于根 window 中的每个小部件,因此如果您只想在 window 作为一个整体获得焦点时做某事,您将需要比较 event.widget
和根 window.
例如:
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()
我有这个代码:
from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()
它只打印一次hello world
,然后就停止工作了。没有了hello world
基本上WM_TAKE_FOCUS
不行
"Note that WM_SAVE_YOURSELF is deprecated, and Tk apps can't implement WM_TAKE_FOCUS or _NET_WM_PING correctly, so WM_DELETE_WINDOW is the only one that should be used"。 这里是a link! 如果您需要始终保持 tkinter 焦点:
w.wm_attributes("-topmost", 1)
做得很好。
您可以将函数绑定到 <FocusIn>
事件。当您绑定到根 window 时,绑定将应用于根 window 中的每个小部件,因此如果您只想在 window 作为一个整体获得焦点时做某事,您将需要比较 event.widget
和根 window.
例如:
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()