如何在Tkinter列表框中直接修改特定專案?


Tkinter是一個基於Python的GUI應用程式開發庫,通常用於構建有用的功能性桌面應用程式。Listbox小部件是另一個Tkinter小部件,用作容器,以列表框的形式顯示專案列表。

要在Listbox小部件中定義專案列表,需要建立一個**Listbox(root, width, height, **options)**建構函式。您可以插入任意數量的專案以在列表框中顯示。

假設您想修改Tkinter Listbox中的特定專案,您可以先建立一個按鈕來選擇要修改的列表中的專案,然後呼叫**delete()**方法刪除其中的任何現有值。刪除值後,您可以將新專案**insert()**到列表框中。讓我們來看一個例子來了解它是如何工作的。

示例

# 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="purple3", foreground="white", font=('Times 13'), selectbackground="white")

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_current():
   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_current).pack()

win.mainloop()

在這個例子中,我們使用Listbox小部件建立了一個專案列表。我們建立了一個名為“編輯”的按鈕,它基本上修改了所選列表專案的現有值。使用此方法,您可以替換/修改Listbox小部件中列表中任何專案的 value。

輸出

執行後,它將生成以下輸出視窗:

現在,從列表中選擇一個專案並單擊“編輯”按鈕。假設您選擇“item5”並單擊“編輯”,則該特定條目將被“foo”替換。

更新於:2021年12月22日

瀏覽量 1K+

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.