如何在 Tkinter.Listbox 中獲取某項的索引?


我們使用 Tkinter 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 ite
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) 的視窗。

從列表中選擇一個專案並單擊 “儲存” 按鈕,以獲取在控制檯中列印的所選專案的索引。

You have selected 3

更新日期:19-Jun-2021

4K+ 瀏覽量

啟動你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.