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

วิธีเปลี่ยนข้อความของไอเท็มใน Tkinter Listbox


เพื่อแสดงรายการไอเท็มในแอปพลิเคชัน Tkinter มี Widget Listbox ใช้สร้างรายการไอเท็มแนวตั้ง เมื่อต้องการเปลี่ยนข้อความของไอเท็ม Listbox เฉพาะตัว ให้เลือกไอเท็มโดยวนลูปผ่าน listbox.curselection() และแทรกไอเท็มใหม่หลังลบ ใช้ listbox.insert(**items) เพื่อแทรกไอเท็ม

ตัวอย่าง

# 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)
lb.pack(expand=True, fill=BOTH)

# Define a function to edit the listbox item
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()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มีรายการไอเท็ม

วิธีเปลี่ยนข้อความของไอเท็มใน Tkinter Listbox

เลือกไอเท็มจากรายการและคลิก "Edit" จะแก้ไขไอเท็มที่เลือกในรายการ

วิธีเปลี่ยนข้อความของไอเท็มใน Tkinter Listbox