Change the focus from one Text widget to another in Tkinter

TkinterServer Side ProgrammingProgramming

In various applications, tkinter widgets are required to be focused to make them active. Widgets can also grab focus and prevent the other events outside the bounds. To manage and give focus to a particular widget, we generally use the focus_set() method. It focuses the widget and makes them active until the termination of the program.


In the following example, we have created two text widgets and we will change the focus from one text widget to another text widget simultaneously using a button widget. Thus, changing the focus is easy by defining two methods which can be handled through the button widgets.

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
#Define a function for changing the focus of text widgets
def changeFocus():
   button.config(command=change_focus, background= "gray71")
def change_focus():
   button.configure(command= changeFocus)
#Create a Text WIdget
text1= Text(win, width= 30, height= 5)
text1.insert(INSERT, "New Line Text")
#Activate the focus
#Create another text widget
text2= Text(win, width= 30, height=5)
text2.insert(INSERT,"Another New Line Text")
#Create a Button
button= Button(win, text= "Change Focus",font=('Helvetica 10 bold'), command= change_focus)


Running the above code will display a window that contains two text widgets. Initially the “text1” widget will have active focus.

Now click the “Change Focus” button to switch the focus between two text widgets.

Published on 15-Apr-2021 13:13:13