Getting a callback when a Tkinter Listbox selection is changed?

bfops picture bfops · Jul 2, 2011 · Viewed 54.7k times · Source

There are a number of ways of getting callbacks when Text or Entry widgets are changed in Tkinter, but I haven't found one for Listbox's (it doesn't help that much of the event documentation I can find is old or incomplete). Is there some way of generating an event for this?

Answer

Pierre-Jean Coudert picture Pierre-Jean Coudert · Oct 17, 2012
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)