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

PythonTkinterServer Side ProgrammingProgramming

Let us assume that we want to check if a particular widget has a focused set or not. The only way to check the widget focus is to use the utility method focus_get(). It returns the object containing the widget’s information which is currently focused on, during the program’s execution. We will use the focus_get() method to find the active widget during our program’s execution.

Example

In this example, we have created an Entry widget that will get its focus when we press the <Enter> key. The focus_get() method will return the current widget’s information which is active.

#Import the Tkinter library
from tkinter import *
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
#Define Event handlers for different Operations
def event_show(event):
   label.config(text="Hello World")
   e.focus_set()
   print("focus is:" ,e.focus_get)
#Create a Label
label= Label(win, text="Press Enter",font=('Helvetica 15 underline'))
label.pack()
#Create an entry widget
e= Entry(win, width= 25)
e.pack(pady=20)
#Bind the function
win.bind('<Return>',lambda event:event_show(event))
win.mainloop()

Output

Running the above code will display a window that contains a button. When we press the <Enter> key, it will print the output containing the widget’s information which is currently focused on the window pane.

Now, when we press <Enter>, it will show the output in the shell as,

focus is : <bound method Misc.focus_get of <tkinter.Entry object .!entry >>
raja
Published on 21-Apr-2021 07:44:34
Advertisements