Tkinter has a number of widgets to provide functionality in any GUI. It also supports a variety of universal widget methods which can be applied on any of the widget.focus_get() and focus_set() methods are also universal widget methods. They can also be applied on Tk() method.
focus_set() method-
This method is used to set the focus on the desired widget if and only if the master window is focused.
Syntax:
widget.focus_set()
Below is the Python program-
# Importing tkinter module# and all functionsfrom tkinter import *Â from tkinter.ttk import *Â Â # creating master windowmaster = Tk()Â Â # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH)Â Â # Button widget which currently has the focuse2 = Button(master, text ="Button")Â Â # here focus_set() method is used to set the focuse2.focus_set()e2.pack(pady = 5)Â Â # Radiobuton widgete3 = Radiobutton(master, text ="Hello")e3.pack(pady = 5)Â Â # Infinite loopmainloop() |
Output:
You may observe in above image that Button widget has the focus. For better understanding copy and run above program.
focus_get() method-
This method returns the name of the widget which currently has the focus.
Syntax:
master.focus_get()
Note: You can use it with any of the widget, master in not necessary.
Below is the Python program –
# Importing tkinter module# and all functionsfrom tkinter import *Â from tkinter.ttk import *Â Â # creating master windowmaster = Tk()Â Â # This method is used to get# the name of the widget# which currently has the focus# by clicking Mouse Button-1def focus(event):Â Â Â Â widget = master.focus_get()Â Â Â Â print(widget, "has focus")Â Â # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH)Â Â # Button Widgete2 = Button(master, text ="Button")e2.pack(pady = 5)Â Â # Radiobutton widgete3 = Radiobutton(master, text ="Hello")e3.pack(pady = 5)Â Â # Here function focus() is binded with Mouse Button-1# so every time you click mouse, it will call the# focus method, defined abovemaster.bind_all("<Button-1>", lambda e: focus(e))Â Â # infinite loopmainloop() |
Output: Every time you click on any widget OR if you click the mouse button-1 above program will print the name of the widget which has the focus. For better understanding copy and run above program.
.!radiobutton has focus .!entry has focus .!button has focus

