Getting a callback when a Tkinter Listbox selection is changed?
def onselect(evt):
# Note here that Tkinter passes an event object to onselect()
w = evt.widget
index = int(w.curselection()[0])
value = w.get(index)
print 'You selected item %d: "%s"' % (index, value)
lb = Listbox(frame, name='lb')
lb.bind('<<ListboxSelect>>', onselect)
You can bind to the <<ListboxSelect>>
event. This event will be generated whenever the selection changes, whether it changes from a button click, via the keyboard, or any other method.
Here's a simple example which updates a label whenever you select something from the listbox:
import tkinter as tk
root = tk.Tk()
label = tk.Label(root)
listbox = tk.Listbox(root)
label.pack(side="bottom", fill="x")
listbox.pack(side="top", fill="both", expand=True)
listbox.insert("end", "one", "two", "three", "four", "five")
def callback(event):
selection = event.widget.curselection()
if selection:
index = selection[0]
data = event.widget.get(index)
label.configure(text=data)
else:
label.configure(text="")
listbox.bind("<<ListboxSelect>>", callback)
root.mainloop()
This event is mentioned in the canonical man page for listbox. All predefined virtual events can be found on the bind man page.