- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
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 win=Tk() # Set the size of the window win.geometry("700x350") # Create a Listbox widget lb=Listbox(win) 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 lb.insert("end","item1","item2","item3","item4","item5") # Add a Button To Edit and Delete the Listbox Item ttk.Button(win, text="Save", command=save).pack() win.mainloop()
Output
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