
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do you check if a widget has a focus in Tkinter?
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 >>
- Related Articles
- How do I give focus to a python Tkinter text widget?
- How to remove focus from a Tkinter widget?
- How to set focus for Tkinter widget?
- Setting the focus to a specific Tkinter entry widget
- How to set focus on Entry widget in Tkinter?
- How to see if a widget exists in Tkinter?
- How do I center the text in a Tkinter Text widget?
- Which widget do you use for an Excel-like table in Tkinter?
- Change the focus from one Text widget to another in Tkinter
- How to center a Tkinter widget?
- Python Tkinter – How do I change the text size in a label widget?
- How do I get the background color of a Tkinter Canvas widget?
- How do you create a clickable Tkinter Label?
- How to update a Button widget in Tkinter?
- How do you check if a variable is an array in JavaScript?
