How to set focus for Tkinter widget?

Tkinter has many inbuilt functions or methods that can be used to extend the functionality of any widget in the application. Sometimes, we need to change or modify the focus of any widget in the application which can be achieved by using the focus_set() method.This method sets the default focus for any widget and makes it active till the execution of the program.


In this example, we will set the focus on first Entry widget where we are required to Enter the name of the User.

#Import the required Libraries
from tkinter import *
from tkinter import ttk

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

#Set the geometry of Tkinter frame

#Define a function to submit the validate the value of Entry widget
def submit_name():
   Label(frame, text="Hello "+ entry1.get(), font=('Helvetica',12, 'bold')).pack(pady=20)
   Label(frame, text= "Your Email is : "+ entry2.get(), font=('Helvetica',12, 'bold')).pack(pady=12)

#Creates a Frame
frame = LabelFrame(win, width= 400, height= 180, bd=3)

#Create an Entry widget in the Frame for Accepting the Username
entry1 = ttk.Entry(frame, width= 40)
entry1.insert(INSERT, "Enter Your Name")
entry1.pack(ipadx= 30, ipady=30)

#Set the focus on Entry1

#Create an Entry Widget to accept the email Address of the User
entry2 = ttk.Entry(frame, width= 40)
entry2.insert(INSERT, "Enter Your Email")

#Create a submit button
submit= ttk.Button(win, text= "submit",command=submit_name)


Run the above code to display two entry widget which has default focus set during the execution of the program.

In the given output, enter the name and Email Address to display the message on the screen.

Updated on: 04-May-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started