ให้เราพิจารณาว่าเราได้สร้างกล่องรายการโดยใช้เมธอด Listbox ใน Tkinter และเราต้องการลบรายการที่เลือกหลายรายการออกจากรายการนี้
ในการเลือกหลายรายการจากกล่องรายการ เราจะใช้ โหมดการเลือก เป็น หลายรายการ . เมื่อวนซ้ำในรายการ เราสามารถดำเนินการลบโดยใช้ปุ่มบางปุ่ม
ตัวอย่าง
#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() ผลลัพธ์
การเรียกใช้โค้ดข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -

ตอนนี้ คุณสามารถเลือกหลายรายการในกล่องรายการและคลิกปุ่ม "ลบ" เพื่อลบรายการเหล่านั้นออกจากรายการ

สังเกตว่า เราได้ลบสามรายการออกจากรายการโดยใช้ปุ่ม "ลบ"