如何清空 Tkinter ListBox?


為了透過可滾動小部件建立一個專案列表,Tkinter 提供了 Listbox 小部件。有了該 Listbox 小部件,我們可以建立一個包含稱為“列表專案”的專案的列表。根據配置,使用者可以從列表中選擇一個或多個專案。

如果想要清除 Listbox 小部件中的專案,我們可以使用 **delete(0, END)** 方法。除了刪除 Listbox 中的所有專案,我們還可以透過從 Listbox 中選擇一個專案(即,使用 **currselection()** 方法選擇一個專案並使用 **delete()** 函式刪除它)來刪除單個專案。

示例

# 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("700x250")

# Create a Listbox widget
lb=Listbox(win, width=100, height=5, font=('TkMenuFont, 20'))
lb.pack()

# Once the list item is deleted, we can insert a new item in the listbox
def delete():
   lb.delete(0,END)
   Label(win, text="Nothing Found Here!",
      font=('TkheadingFont, 20')).pack()

# 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="Delete", command=delete).pack()

win.mainloop()

輸出

如果執行上述程式碼,它將在列表框中顯示一個專案列表和一個按鈕以清除 Listbox。

現在,單擊“Delete”按鈕以清除 Listbox 小部件。

更新於: 05-8-2021

12K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.