What is the difference between focus and focus_set methods in Tkinter?


Focus is used to refer to the widget or window which is currently accepting input. Widgets can be used to restrict the use of mouse movement, grab focus, and keystrokes out of the bounds. However, if we want to focus a widget so that it gets activated for input, then we can use focus.set() method. focus() is sometimes referred to as focus_set().

focus_set() focuses on the widget when its window or widget gets focus.

Example

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

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Define a function to set the focus
def set_focus():
   entry.focus_set()

# Create an Entry widget
entry=Entry(win, width=35)
   entry.pack()

# Create a Button to get the focus on any widget
ttk.Button(win, text="Set Focus", command=set_focus).pack()

win.mainloop()

Output

Executing the above code will display a window that contains a Button and an Entry widget. When we click the button, it will set the focus on the Entry Widget.

Updated on: 18-Jun-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements