2013-10-30 81 views
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 

有人知道如何從列表框中刪除未選中的東西呢?

+0

格式的代碼正確。 –

+0

什麼不起作用?什麼是'我'? – martineau

+0

你可能會更好,只是用一個只包含當前選擇的新列表來代替'llista',而不是刪除除了它之外的其他所有東西。如果它是一個簡單的'list'對象,則相當於'llista = [llista.curselection()]'。 – martineau

回答

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()