เราใช้ Widget Listbox ของ Tkinter เพื่อสร้างรายการไอเท็ม แต่ละไอเท็มใน listbox มีดัชนีที่กำหนดตามลำดับแนวตั้ง
สมมติว่าต้องการหาดัชนีของไอเท็มที่คลิกใน listbox เราต้องสร้างปุ่มที่จับการเลือกปัจจุบันด้วยเมธอด list.curselection() แล้วพิมพ์ดัชนีด้วยเมธอด get()
ตัวอย่าง
# Import the required libraries
from tkinter import *
# 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, font=('Times 13'), selectbackground="black")
lb.pack()
# Define a function to edit the listbox item
def save():
for item in lb.curselection():
print("You have selected " + str(item+1))
# Add items in the Listbox
lb.insert("end", "A", "B", "C", "D", "E", "F")
# Add a Button To Edit and Delete the Listbox Item
Button(win, text="Save", command=save).pack()
win.mainloop()ผลลัพธ์
การรันโค้ดจะแสดงหน้าต่างที่มีรายการอักษร (A-F)

เลือกไอเท็มจากรายการและคลิกปุ่ม "Save" เพื่อได้ดัชนีของไอเท็มที่เลือกพิมพ์บนคอนโซล
You have selected 3