How to get the widget name in the event in Tkinter?


Tkinter is a Python library that is used to create and develop functional GUI-based applications. Tkinter provides widgets that can be used for constructing the visual and functional representation of the application.

Let us suppose that we have defined some widgets in our application. If we want to get a widget's name in an event, then it can be achieved by using event.widget["text"] keywords inside a function. We can print the name by using it inside the print() function.

Example

# Import the required libraries
from tkinter import *

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

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

# Define a function to delete the shape
def on_click():
   print (win.winfo_children())

# Create a canvas widget
canvas=Canvas(win, width=500, height=300)
canvas.pack()

# Create a button to delete the button
Button(win, text="Click", command=on_click).pack()

win.mainloop()

Output

If we run the above code, it will display a window with a button.

If we click the button, the output will show the name of the widget on the screen.

[<tkinter.Canvas object .!canvas>, <tkinter.Button object .!button>]

Updated on: 06-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements