Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you check if a widget has a focus in Tkinter?
In Tkinter, you can check if a widget has focus using the focus_get() method. This method returns the widget object that currently has focus, allowing you to compare it with your target widget to determine if it's focused.
Using focus_get() Method
The focus_get() method is called on the root window and returns the currently focused widget object. You can compare this returned object with your widget to check if it has focus ?
import tkinter as tk
# Create main window
root = tk.Tk()
root.geometry("400x300")
root.title("Focus Check Example")
# Create widgets
entry1 = tk.Entry(root, width=20)
entry1.pack(pady=10)
entry2 = tk.Entry(root, width=20)
entry2.pack(pady=10)
result_label = tk.Label(root, text="Click on an entry field", bg="lightgray")
result_label.pack(pady=20)
def check_focus():
focused_widget = root.focus_get()
if focused_widget == entry1:
result_label.config(text="Entry 1 has focus", bg="lightgreen")
elif focused_widget == entry2:
result_label.config(text="Entry 2 has focus", bg="lightblue")
else:
result_label.config(text="No entry field has focus", bg="lightcoral")
# Button to check focus
check_button = tk.Button(root, text="Check Focus", command=check_focus)
check_button.pack(pady=10)
root.mainloop()
Checking Focus with Event Binding
You can also bind focus events to automatically detect when a widget gains or loses focus ?
import tkinter as tk
root = tk.Tk()
root.geometry("400x250")
root.title("Focus Events Example")
status_label = tk.Label(root, text="Status: No widget focused", bg="white", relief="sunken")
status_label.pack(pady=10, fill="x", padx=10)
def on_focus_in(event):
widget_name = event.widget.winfo_name()
status_label.config(text=f"Widget '{widget_name}' gained focus", bg="lightgreen")
def on_focus_out(event):
widget_name = event.widget.winfo_name()
status_label.config(text=f"Widget '{widget_name}' lost focus", bg="lightcoral")
# Create entry widgets with focus event bindings
entry1 = tk.Entry(root, name="entry1")
entry1.pack(pady=5)
entry1.bind("<FocusIn>", on_focus_in)
entry1.bind("<FocusOut>", on_focus_out)
entry2 = tk.Entry(root, name="entry2")
entry2.pack(pady=5)
entry2.bind("<FocusIn>", on_focus_in)
entry2.bind("<FocusOut>", on_focus_out)
# Button to demonstrate focus change
tk.Button(root, text="Click me to change focus").pack(pady=10)
root.mainloop()
Practical Example with Focus Validation
Here's a practical example that validates input when a field loses focus ?
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.geometry("350x200")
root.title("Focus Validation Example")
def validate_email(event):
email = email_entry.get()
if "@" not in email and email:
messagebox.showwarning("Invalid Email", "Please enter a valid email address")
email_entry.focus_set() # Return focus to the field
def check_current_focus():
focused = root.focus_get()
if focused:
widget_type = focused.__class__.__name__
result_label.config(text=f"Current focus: {widget_type}")
else:
result_label.config(text="No widget has focus")
tk.Label(root, text="Email:").pack(pady=5)
email_entry = tk.Entry(root, width=30)
email_entry.pack(pady=5)
email_entry.bind("<FocusOut>", validate_email)
tk.Label(root, text="Password:").pack(pady=5)
password_entry = tk.Entry(root, width=30, show="*")
password_entry.pack(pady=5)
result_label = tk.Label(root, text="Click to check focus", bg="lightgray")
result_label.pack(pady=10)
check_btn = tk.Button(root, text="Check Current Focus", command=check_current_focus)
check_btn.pack(pady=5)
root.mainloop()
Key Methods for Focus Management
| Method | Purpose | Returns |
|---|---|---|
focus_get() |
Get currently focused widget | Widget object or None |
focus_set() |
Set focus to a widget | None |
focus_force() |
Force focus to a widget | None |
Conclusion
Use focus_get() to check which widget currently has focus by comparing the returned object with your target widget. Combine this with focus events like <FocusIn> and <FocusOut> for dynamic focus tracking and validation.
