Getting a callback when a Tkinter Listbox selection is changed?

Getting a callback when a Tkinter Listbox selection is changed ?

Asked on November 28, 2018 in tkinter.
Add Comment


  • 5 Answer(s)

    The best solution is:

    <<ListboxSelect>>
    
    Answered on November 28, 2018.
    Add Comment

    You can try this :

    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)
    
    Answered on November 28, 2018.
    Add Comment

    Here the answer:

        The problem that I needed to get the last selected item in a listbox with selectmode=MULTIPLE. In case someone else has the same problem, here is what I did:

    lastselectionList = []
    def onselect(evt):
        # Note here that Tkinter passes an event object to onselect()
        global lastselectionList
        w = evt.widget
        if lastselectionList: #if not empty
        #compare last selectionlist with new list and extract the difference
            changedSelection = set(lastselectionList).symmetric_difference(set(w.curselection()))
            lastselectionList = w.curselection()
        else:
        #if empty, assign current selection
            lastselectionList = w.curselection()
            changedSelection = w.curselection()
        #changedSelection should always be a set with only one entry, therefore we can convert it to a lst and extract                                                                                                                                                                                                                         first entry
        index = int(list(changedSelection)[0])
        value = w.get(index)
        tkinter.messagebox.showinfo("You selected ", value)
    listbox = tk.Listbox(frame,selectmode=tk.MULTIPLE)
    listbox.bind('<<ListboxSelect>>', onselect)
    listbox.pack()
    
    Answered on November 28, 2018.
    Add Comment

    You can bind to:

    <<ListboxSelect>>
    Answered on February 25, 2019.
    Add Comment

    In Python 3.6.5, int(w.curselection()[0]) can be replaced with w.curselection()[0] because it already returns an object of type int. Notice that I didn’t try this with any other Python version

    Answered on April 17, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.