Disable focus for tkinter widgets – Python
Prerequisite: Python-Tkinter
In this article, we will discuss how to disable the focus from the widgets in the Tkinter framework. For disabling the focus, we use takefocus option inside the widget and assign its value to 0.
Stepwise implementation:
Step1: Import Tkinter and initialize tkinter window
Python3
import tkinter as tk
root = tk.Tk()
root.geometry( "300x300" )
root.mainloop()
|
Step 2: Add some widgets to the application
# Creating button widget
btn = tk.Button(root, text=”Button”) # initializing the widget.
btn.pack() # calling the widget in application
Code:
Python3
import tkinter as tk
root = tk.Tk()
root.geometry( "300x300" )
btn = tk.Button(root, text = "I am button" )
btn.pack()
txt = tk.Entry(root, width = 10 )
txt.pack()
rb = tk.Radiobutton(root, text = "I am radio button" )
rb.pack()
cb = tk.Checkbutton(root, text = "I am check button" )
cb.pack()
root.mainloop()
|
Output:
Here we notice that we are getting focus on each widget after pressing the TAB key.
Step-3: Adding disable focus functionality to our program.
We use takefocus argument for disabling the focus
Syntax: takefocus = 0
# for button
btn = tk.Button(root, text="Button", takefocus=0)
The approach of the program is to disable the focus from the widgets with the help takefocus argument. We put its value to 0 for doing so. Other widgets have their focus enabled.
Code:
Python3
import tkinter as tk
root = tk.Tk()
root.geometry( "300x300" )
btn = tk.Button(root, text = "I am button" )
btn.pack()
btn_no_focus = tk.Button(root, text = "I am not focused" ,
takefocus = 0 ,foreground = "red" )
btn_no_focus.pack()
txt = tk.Entry(root, width = 10 )
txt.pack()
txt = tk.Entry(root, width = 10 , takefocus = 0 )
txt.pack()
rb = tk.Radiobutton(root, text = "I am radio button" )
rb.pack()
rb_unfocus = tk.Radiobutton(root, text = "I am unfocused radio button" ,
takefocus = 0 ,foreground = "red" )
rb_unfocus.pack()
cb = tk.Checkbutton(root, text = "I am check button" )
cb.pack()
cb_unfocused = tk.Checkbutton(root, text = "I am unfocused check button" ,
takefocus = 0 , foreground = "red" )
cb_unfocused.pack()
root.mainloop()
|
Output:
Red-colored widgets have takefocus=0 and others don’t have this argument. The red color is only used for clarity you may also remove it.
Last Updated :
05 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...