python 如何检查小部件在 Tkinter 中是否具有焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1385921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you check if a widget has focus in Tkinter?
提问by cstack
from Tkinter import *
app = Tk()
text_field = Entry(app)
text_field.pack()
app.mainloop()
I want to be able to check if text_field
is currently selected or focused, so that I know whether or not to do something with its contents when the user presses enter.
我希望能够检查text_field
当前是否被选中或聚焦,以便我知道当用户按下 Enter 键时是否对其内容进行处理。
回答by Bryan Oakley
If you want to do something when the user presses enter only if the focus is on the entry widget, simply add a binding to the entry widget. It will only fire if that widget has focus. For example:
如果您想在用户按下 Enter 键时执行某些操作,仅当焦点位于条目小部件上时,只需向条目小部件添加绑定即可。仅当该小部件具有焦点时才会触发。例如:
import tkinter as tk
root = tk.Tk()
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e1.pack()
e2.pack()
def handleReturn(event):
print("return: event.widget is",event.widget)
print("focus is:", root.focus_get())
e1.bind("<Return>", handleReturn)
Notice that the handler is only called if the first entry has focus when you press return.
请注意,只有在按回车键时第一个条目具有焦点时才会调用处理程序。
If you really want a global binding and need to know which widget has focus, use the focus_get() method on the root object. In the following example a binding is put on "." (the main toplevel) so that it fires no matter what has focus:
如果您真的想要全局绑定并且需要知道哪个小部件具有焦点,请在根对象上使用 focus_get() 方法。在以下示例中,绑定放在“.”上。(主要的顶层),以便它无论有什么焦点都会触发:
import tkinter as tk
root = tk.Tk()
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e1.pack()
e2.pack()
def handleReturn(event):
print("return: event.widget is",event.widget)
print("focus is:",root.focus_get())
root.bind("<Return>", handleReturn)
Notice the difference between the two: in the first example, the handler will only be called when you press return in the first entry widget. There is no need to check which widget has focus. In the second example, the handler will be called no matter which widget has focus.
请注意两者之间的区别:在第一个示例中,仅当您在第一个条目小部件中按 return 时才会调用处理程序。无需检查哪个小部件具有焦点。在第二个示例中,无论哪个小部件具有焦点,都会调用处理程序。
Both solutions are good depending on what you really need to have happened. If your main goal is to only do something when the user presses return in a specific widget, use the former. If you want a global binding, but in that binding do something different based on what has or doesn't have focus, do the latter example.
两种解决方案都很好,具体取决于您真正需要发生的事情。如果您的主要目标是仅在用户按特定小部件中的返回键时执行某些操作,请使用前者。如果您想要一个全局绑定,但在该绑定中根据具有或不具有焦点的内容执行不同的操作,请执行后一个示例。