Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีลบรายการที่เลือกหลายรายการใน Listbox Tkinter

สมมติว่าเราสร้าง Listbox ด้วยเมธอด Listbox ใน Tkinter และต้องการลบรายการที่เลือกหลายรายการจาก List นี้

เพื่อเลือกหลายรายการจาก Listbox เราจะใช้ selectmode เป็น MULTIPLE ตอนนี้วนลูปผ่าน List เราสามารถทำการลบได้โดยใช้ปุ่มบางปุ่ม

ตัวอย่าง

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

ผลลัพธ์

การรันโค้ดข้างต้นจะให้ผลลัพธ์ดังนี้:

วิธีลบรายการที่เลือกหลายรายการใน Listbox Tkinter

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

วิธีลบรายการที่เลือกหลายรายการใน Listbox Tkinter

สังเกต ที่นี่เราลบ 3 รายการออกจาก List โดยใช้ปุ่ม "Delete"