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

วิธีแก้ไขรายการใน Tkinter Listbox


Widget Listbox ของ Tkinter ใช้สร้างรายการไอเท็ม สามารถเก็บตัวเลข ตัวอักษร และรองรับฟีเจอร์มากมาย เช่น การเลือกและแก้ไขรายการ

เพื่อแก้ไขรายการใน Listbox ให้เลือกไอเท็มในลูปด้วยฟังก์ชัน listbox.curselection() แล้วแทรกไอเท็มใหม่หลังลบไอเท็มเดิม ใช้ listbox.insert(**items) เพื่อแทรกไอเท็มใหม่

ตัวอย่าง

ในตัวอย่างนี้ สร้างรายการใน listbox และใช้ปุ่มแก้ไขไอเท็มที่เลือก

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")

# Create a Listbox widget
lb = Listbox(win, width=100, height=10, background="purple2", foreground="white", font=('Times 13'), selectbackground="black")
lb.pack()

# Select the list item and delete the item first
# Once the list item is deleted, we can insert a new item in the listbox
def edit():
    for item in lb.curselection():
        lb.delete(item)
        lb.insert("end", "foo")

# Add items in the Listbox
lb.insert("end", "item1", "item2", "item3", "item4", "item5")

# Add a Button To Edit and Delete the Listbox Item
ttk.Button(win, text="Edit", command=edit).pack()

win.mainloop()

ผลลัพธ์

การรันโค้ดจะให้คุณเลือกและแก้ไขรายการใน listbox

วิธีแก้ไขรายการใน Tkinter Listbox

คุณสามารถกำหนดค่ารายการโดยคลิกปุ่ม "Edit"

วิธีแก้ไขรายการใน Tkinter Listbox