
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change Focus Between Text Widgets in Tkinter
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.
Example
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 win.geometry("750x250") #Define a function for changing the focus of text widgets def changeFocus(): text1.focus_set() button.config(command=change_focus, background= "gray71") def change_focus(): text2.focus_set() button.configure(command= changeFocus) #Create a Text WIdget text1= Text(win, width= 30, height= 5) text1.insert(INSERT, "New Line Text") #Activate the focus text1.focus_set() text1.pack() #Create another text widget text2= Text(win, width= 30, height=5) text2.insert(INSERT,"Another New Line Text") text2.pack() #Create a Button button= Button(win, text= "Change Focus",font=('Helvetica 10 bold'), command= change_focus) button.pack(pady=20) win.mainloop()
Output
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.