如何检查小部件在 Tkinter 中是否具有焦点? [英] How do you check if a widget has focus in Tkinter?

查看:22
本文介绍了如何检查小部件在 Tkinter 中是否具有焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from Tkinter import *

app = Tk()
text_field = Entry(app)
text_field.pack()
app.mainloop()

我希望能够检查 text_field 当前是否被选中或聚焦,以便我知道当用户按下 Enter 键时是否对其内容进行处理.

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.

推荐答案

如果您想在用户按下 Enter 键时仅在焦点位于条目小部件上时执行某些操作,只需向条目小部件添加绑定即可.仅当该小部件具有焦点时才会触发.例如:

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:

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)

root.mainloop()

请注意,只有在按下回车键时第一个条目具有焦点时才会调用处理程序.

Notice that the handler is only called if the first entry has focus when you press return.

如果你真的想要一个全局绑定并且需要知道哪个小部件有焦点,请在根对象上使用 focus_get() 方法.在以下示例中,将绑定放在."上.(主要的顶层)所以它会在有焦点的情况下触发:

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:

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)

root.mainloop()

注意两者之间的区别:在第一个示例中,仅当您在第一个条目小部件中按 return 时才会调用处理程序.无需检查哪个小部件具有焦点.在第二个示例中,无论哪个小部件具有焦点,都会调用处理程序.

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.

这篇关于如何检查小部件在 Tkinter 中是否具有焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆