How to set the tab order in a Tkinter application?

TkinterPythonGUI-Programming

The Tab order in any application decides which element of the application have to set focus. In a Tkinter application, it constantly looks for the next widget that needs to be focused on. To set the tab order in the application, we can define a function and pick all the widgets and use lift() method. It will allow the function to set the focus on a particular widget programmatically.

Example

#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("700x350")

#Add entry widgets
e1 = Entry(win, width= 35, bg= '#ac12ac', fg= 'white')
e1.pack(pady=10)
e2 = Entry(win, width= 35)
e2.pack(pady=10)
e3 = Entry(win, width= 35, bg= '#aa23dd',fg= 'white')
e3.pack(pady=10)

#Change the tab order
def change_tab():
   widgets = [e3,e2,e1]
   for widget in widgets:
      widget.lift()

#Create a button to change the tab order
Button(win, text="Change Order", font=('Helvetica 11'), command= change_tab).pack()
win.mainloop()

Output

Running the above code will display a window with a set of Entry widgets and a button to change the Tab order of each widget.

raja
Published on 26-May-2021 12:03:01
Advertisements