GuinovartD
GuinovartD

Reputation: 1

delete unselected items from listbox

I need to set a button that deletes un-selected things from a listbox. I got this code:

def delete_unselected():
    pos = 0
    for i in llista:
        if llista(pos) != llista.curselection():
            del = llista(pos)
            llista.delete( del,del )
            pos = pos + 1

Someone knows how to delete the un-selected things from the listbox?

Upvotes: 0

Views: 234

Answers (1)

Theuns Alberts
Theuns Alberts

Reputation: 330

You do not specify the GUI framework you are using, but seeing llista.curselection() I assume you are using Tkinter.

Herewith a complete example:

from Tkinter import *

def on_delete_click():
    # Get the indices selected, make them integers and create a set out of it
    indices_selected = set([int(i) for i in lb.curselection()])
    # Create a set with all indices present in the listbox
    all_indices = set(range(lb.size()))
    # Use the set difference() function to get the indices NOT selected
    indices_to_del = all_indices.difference(indices_selected)
    # Important to reverse the selection to delete so that the individual
    # deletes in the loop takes place from the end of the list.
    # Else you have this problem:
    #   - Example scenario: Indices to delete are list entries 0 and 1
    #   - First loop iteration: entry 0 gets deleted BUT now the entry at 1
    #     becomes 0, and entry at 2 becomes 1, etc
    #   - Second loop iteration: entry 1 gets deleted BUT this is actually
    #     theh original entry 2
    #   - Result is the original list entries 0 and 2 got deleted instead of 0
    #     and 1
    indices_to_del = list(indices_to_del)[::-1]
    for idx in indices_to_del:
        lb.delete(idx)

if __name__ == "__main__":
    gui = Tk("")
    lb = Listbox(gui, selectmode="extended") # <Ctrl>+click to multi select
    lb.insert(0, 'Apple')
    lb.insert(1, 'Pear')
    lb.insert(2, 'Bananna')
    lb.insert(3, 'Guava')
    lb.insert(4, 'Orange')
    lb.pack()

    btn_del = Button(gui, text="Delete unselected", command=on_delete_click)
    btn_del.pack()

    gui.mainloop()

Upvotes: 1

Related Questions