如何在 Tkinter 中刪除列表框中選定的多項?
假設我們已經使用 Tkinter 中的 Listbox 方法建立了一個列表框,並且我們想要從此列表中刪除多個選定項。
為了從列表框中選擇多個列表,我們將使用 selectmode 作為 MULTIPLE。現在,透過列表進行迭代,我們可以使用某些按鈕執行刪除操作。
示例
#Import the required libraries from tkinter import * #Create an instance of tkinter frame or window win= Tk() #Set the geometry win.geometry("700x400") #Create a text Label label= Label(win, text="Select items from the list", font= ('Poppins bold', 18)) label.pack(pady= 20) #Define the function def delete_item(): selected_item= my_list.curselection() for item in selected_item[::-1]: my_list.delete(item) my_list= Listbox(win, selectmode= MULTIPLE) my_list.pack() items=['C++','java','Python','Rust','Ruby','Machine Learning'] #Now iterate over the list for item in items: my_list.insert(END,item) #Create a button to remove the selected items in the list Button(win, text= "Delete", command= delete_item).pack() #Keep Running the window win.mainloop()
輸出
執行上述程式碼將生成以下輸出 -
現在,您可以在列表框中選擇多個條目,然後單擊“刪除”按鈕以從列表中移除這些條目。
觀察一下,在這裡,我們透過使用“刪除”按鈕從列表中刪除了三個條目。
廣告