How to check type of a Tkinter Widget

Often when dealing with alot of Tkinter widgets, you will need a way to distinguish between them based on their widget type (Entry, Frame, Label etc.) In this Tkinter tutorial, we will show you two different methods to check for the type of a Tkinter Widget.


Checking type of tkinter widget

First method, which is very commonly used in Python for determining the type of objects is the isinstance() function.

The first parameter in this function is the object whose type we want to check, and in the second parameter we place the name of the Class against which we are checking it. Returns True or False depending on whether the object (in the first parameter) is an object of the specified Class (in the second parameter)

import tkinter as tk

root = tk.Tk()
root.geometry('200x150')

mylabel = tk.Label(root, text="Hello World")
mylabel.pack()

if isinstance(mylabel, tk.Label):
    print("This is a Label")
else:
    print("This is not a Label")

root.mainloop()
print("This is a Label")

Don’t mess up the name of the Class. If you import Tkinter as “tk”, then we write tk.Label. If you imported tkinter directly (without renaming it) then we would write tkinter.Label.


Lets take a look at a second method using the winfo_class() method. All tkinter objects have this method, which returns a string specifying their type.

import tkinter as tk

root = tk.Tk()
root.geometry('200x150')

mylabel = tk.Label(root, text="Hello World")
mylabel.pack()

if mylabel.winfo_class() == 'Label':
    print("This is a Label")
else:
    print("This is not a Label")

root.mainloop()
print("This is a Label")

Alternatively, you can also use the type(object) function to return a string for an object, but the string it returns is a bit complicated and a bit hard to place in an if-statement. Better if you just follow the above method using winfo_class().


This marks the end of the How to check type of a Tkinter Widget? Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the Tutorial content can be asked in the comments section below.

Leave a Comment