簡體   English   中英

如何刪除列表框中的多個選定項目 - 使用 Python Tkinter

[英]How to delete multiple selected item in a listBox - with Python Tkinter

為了從我的 listBox 中刪除項目,我使用了一個循環,但它只刪除了第一個選定的項目。 我不能使用Listbox.delete(i,j,k)因為我不能將我的元組“索引”作為 Listbox.delete() 的參數傳遞。 請需要幫助。

def App():
root=Tk()
operatorList=tk.Listbox(root,selectmode="MULTIPLE")
operatorList.pack()

#binding the Listbox
conn = sqlite3.connect('C:/Users/Stagiaire/Desktop/Ketrika/VCbase.db')
cursor=conn.cursor()
cursor.execute("SELECT operatorId,operatorName from Operator")
OpRecord=cursor.fetchall()
conn.close()
i=0
for operator in OpRecord:
    operatorList.insert(i,operator)
    i=i+1
workingOperator=[]

def CmdSelect():
    index=operatorList.curselection()
    for i in index:
        o=operatorList.get(i)
        workingOperator.append(o)
        operatorList.delete(i)
    
SelectButton=Button(root,text="Select",command=SelectCmd)   
SelectButton.pack()
root.mainloop()

您實際上已經刪除了您選擇的項目數量,但不是您期望的項目。 這是因為在您刪除第一個選中的項目后,其余項目的索引已更改。 然后當你刪除第二個選中的項目時,它實際上會刪除它后面的項目。

您需要以相反的順序刪除項目:

def CmdSelect():
    tmp = []
    for i in operatorList.curselection()[::-1]:
        tmp.append(operatorList.get(i))
        operatorList.delete(i)
    workingOperator.extend(tmp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM