Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to capture events on Tkinter child widgets?
When building interactive Tkinter applications, you often need to capture events on child widgets like buttons, listboxes, or entry fields. This involves creating callback functions that respond to user interactions such as clicks, selections, or key presses.
Understanding Event Handling
Event handling in Tkinter works through callback functions ? functions that execute when specific events occur. You connect these functions to widgets using parameters like command for buttons or by binding events directly.
Example: Capturing Listbox Selection Events
Let's create a Listbox widget that captures selection events. When a user selects an item and clicks a button, we'll display which item was chosen ?
# 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 capture the listbox selection
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 capture the selection event
ttk.Button(win, text="Save", command=save).pack()
win.mainloop()
How It Works
The save() function uses lb.curselection() to get the indices of selected items. When you select an item and click "Save", it prints the selection to the console ?
You have selected 3
Alternative: Direct Event Binding
You can also bind events directly to widgets without needing a separate button ?
from tkinter import *
win = Tk()
win.geometry("400x300")
# Create a Listbox
lb = Listbox(win)
lb.pack(expand=True, fill=BOTH)
# Function to handle selection event
def on_select(event):
selection = lb.curselection()
if selection:
item = lb.get(selection[0])
print(f"Selected: {item}")
# Bind the selection event
lb.bind("<<ListboxSelect>>", on_select)
# Add items
items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
for item in items:
lb.insert("end", item)
win.mainloop()
Common Event Types
| Event | Description | Usage |
|---|---|---|
<Button-1> |
Left mouse click | widget.bind("<Button-1>", function) |
<<ListboxSelect>> |
Listbox selection change | listbox.bind("<<ListboxSelect>>", function) |
<KeyPress> |
Any key pressed | widget.bind("<KeyPress>", function) |
command |
Button click (parameter) | Button(command=function) |
Conclusion
Capturing events on Tkinter child widgets involves creating callback functions and connecting them using command parameters or bind() methods. Use curselection() for listbox selections and event binding for more complex interactions.
