0

リストボックスから選択されていないものを削除するボタンを設定する必要があります。私はこのコードを得ました:

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

リストボックスから選択されていないものを削除する方法を知っている人はいますか?

4

1 に答える 1

1

使用している GUI フレームワークを指定していませんが、llista.curselection()を見ると、Tkinter を使用していると思われます。

以下に完全な例を示します。

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()
于 2013-10-30T11:06:26.683 に答える