To active the focus on a particular widget during the execution of a Tkinter program, we can use focus_set() method. Adding the focus creates a gray line around the widget and makes it visible to the user.
There might be some cases when we need to remove the focus from the desired widget.
This can be done either by removing the focus_set() property or switching the focus from one widget to another.
#Import the required Libraries from tkinter import * from tkinter import ttk from tkinter import messagebox #Create an instance of Tkinter frame win = Tk() #Set the geometry of Tkinter Frame win.geometry("750x250") #Define a function to show the message def logged_in(): messagebox.showinfo("Message", "Successfully Logged In!") win.destroy() #Define a Label widget Label(win, text= "Login to the System", font=('Aerial', 14, 'bold')).pack(pady=15) #Create an entry widget Label(win, text="Enter Username").pack() username= Entry(win, width= 20) username.pack() Label(win, text= "Enter passowrd").pack() password= Entry(win, show="*", width= 20) password.pack() password.focus_set() #Add a Bottom widget button=ttk.Button(win, text="Login", command= logged_in) button.pack(pady=13) #Create a Button widget win.mainloop()
In the above code snippet, the focus is currently set to the Password Entry Field, which can be unset or switched by adding focus_set() to another widget.