【问题标题】:How to delete multiple selected item in a listBox - with Python Tkinter如何删除列表框中的多个选定项目 - 使用 Python Tkinter
【发布时间】:2021-01-21 08:11:23
【问题描述】:

为了从我的列表框中删除项目,我使用了一个循环,但它只删除了第一个选定的项目。我不能使用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()

【问题讨论】:

    标签: python tkinter listbox


    【解决方案1】:

    您实际上删除了您选择的项目数量,但不是您期望的项目。这是因为在您删除第一个选中项后,其余项的索引已更改。那么当你删除第二个选中项时,它实际上会删除它后面的项。

    您需要以相反的顺序删除项目:

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

    【讨论】:

    • 我希望的最有效的解决方案!谢谢你:)
    猜你喜欢
    • 2017-12-02
    • 2019-04-06
    • 1970-01-01
    • 2011-10-27
    • 2012-03-17
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多