从列表框中删除未选择的项目

时间:2013-10-30 08:43:49

标签: python listbox tkinter

我需要设置一个按钮,从列表框中删除未选中的内容。 我得到了这段代码:

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

有人知道如何从列表框中删除未选择的内容吗?

1 个答案:

答案 0 :(得分: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()