35 lines
906 B
Python
35 lines
906 B
Python
import tkinter as tk
|
|
from tkinter import messagebox
|
|
|
|
def on_select(event):
|
|
# Get selected item's index
|
|
selection = listbox.curselection()
|
|
if selection:
|
|
index = selection[0]
|
|
# Get the selected item
|
|
item = listbox.get(index)
|
|
# Update label or show a message
|
|
label.config(text=f"Selected: {item}")
|
|
# Or display a message box
|
|
# messagebox.showinfo("Selection", f"You selected: {item}")
|
|
|
|
root = tk.Tk()
|
|
root.title("Listbox Example")
|
|
|
|
# Sample list of items
|
|
items = ["Apple", "Ban Banana", "Cherry", "Date", "Elderberry"]
|
|
|
|
# Create a Listbox widget
|
|
listbox = tk.Listbox(root)
|
|
for item in items:
|
|
listbox.insert(tk.END, item)
|
|
listbox.pack(padx=10, pady=10)
|
|
|
|
# Bind the select event
|
|
listbox.bind('<<ListboxSelect>>', on_select)
|
|
|
|
# Label to display selected item
|
|
label = tk.Label(root, text="Select an item")
|
|
label.pack(pady=5)
|
|
|
|
root.mainloop() |