在 Tkinter 中如何检查小部件是否具有焦点?
from Tkinter import *
app = Tk()
text_field = Entry(app)
text_field.pack()
app.mainloop()
我希望能够检查 text_field
当前是否被选中或聚焦,以便我知道当用户按 Enter 键时是否对其内容执行某些操作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只想在焦点位于条目小部件上时用户按下 Enter 时执行某些操作,只需向条目小部件添加绑定即可。仅当该小部件具有焦点时才会触发。例如:
请注意,只有当您按回车键时第一个条目获得焦点时,才会调用处理程序。
如果您确实想要全局绑定并且需要知道哪个小部件具有焦点,请在根对象上使用 focus_get() 方法。在下面的示例中,绑定被放置在“.”上。 (主顶层),以便无论焦点是什么都会触发:
请注意两者之间的区别:在第一个示例中,仅当您在第一个条目小部件中按回车键时才会调用处理程序。无需检查哪个小部件具有焦点。在第二个示例中,无论哪个小部件具有焦点,都会调用处理程序。
这两种解决方案都很好,具体取决于您真正需要发生的事情。如果您的主要目标是仅当用户在特定小部件中按回车键时执行某些操作,请使用前者。如果您想要一个全局绑定,但在该绑定中根据具有或不具有焦点的内容执行不同的操作,请执行后一个示例。
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:
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:
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.
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.