How to capture events on Tkinter child widgets?

Suppose we are creating an application that interacts with the user clicks on the Button visible in the application. To understand how exactly events work, we have to create a callback function as well as a trigger that will execute an event. Whenever the user clicks the button, the event happens and it needs to be captured on the screen.


In this example, we will create a Listbox widget that will have a list of items in it. When we select an item, then it will capture what the user has clicked. To figure out the captured event, we can use the print() function to print on the screen.

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

# Create an instance of tkinter frame or window

# Set the size of the window

# Create a Listbox widget
lb.pack(expand=True, fill=BOTH)

# Define a function to edit the listbox ite
def save():
   for item in lb.curselection():
      print("You have selected "+ str(item+1))

# Add items in the Listbox

# Add a Button To Edit and Delete the Listbox Item
ttk.Button(win, text="Save", command=save).pack()



Executing the above code will display a window with a list of items in it. If we click the "Save" button, it will tell us what event has been captured.

Now, select and item from the list and click the "Save" button. It will print on the console the item you have selected.

You have selected 3