Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

python - How do you check if a widget has focus in Tkinter?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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()

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...