Search code examples
pythontkinter

Can I make a tkinter.listbox item exclusive from the rest?


So I have a listbox where the user can select multiple items, based on an array made from files in a folder.

Now I need to make an "All"-Item, which should remove the selection from all other items in the list. So basically a selectmode=multiple, with the ability to make that one item exclusive (like shown in the picture below).

Is that possible at all? two pictures of a tkinter-listbox, side by side. Left one has multiple items selected, the right one has just one selected


Solution

  • That is possible using <<ListboxSelect>> event handler, select_clear function and a custom flag variable.

    If a user changes selection and All was previously selected then All should be unselected and the all_selected flag should become False.

    When All is selected and the flag is False then the rest of the items should be unselected and the all_selected flag should become True.

    from tkinter import *
     
    top = Tk()
     
    listbox = Listbox(top, selectmode = 'multiple')
    listbox.pack_configure(padx = 30, pady = 10)
    
    items = ['foo', 'bar', 'baz', 'qux']
    
    listbox.insert(0, *items)
    listbox.insert(listbox.size(), 'All')
    listbox.all_selected = False
    
    def on_listbox_select(event):
        lbox = event.widget
        last = lbox.size() - 1
    
        if lbox.all_selected:
            lbox.select_clear(last)
            lbox.all_selected = False
            return
        
        if last in lbox.curselection():
            lbox.select_clear(0, last - 1)
            lbox.all_selected = True
        
    listbox.bind('<<ListboxSelect>>', on_listbox_select)
    
    button = Button(top, text = 'Do some stuff') 
    button.pack_configure(pady = 10)
    
    listbox.pack() 
    button.pack()
     
    top.mainloop()