How to clear a Tkinter ListBox?


To create a list of items with a scrollable widget, Tkinter provides the Listbox widget. With the Listbox widget, we can create a list that contains items called List items. Depending upon the configuration, the user can select one or multiple items from the list.

If we want to clear the items in the Listbox widget, we can use the delete(0, END) method. Besides deleting all the items in the Listbox, we can delete a single item as well by selecting an item from the Listbox, i.e., by using currselection() method to select an item and delete it using the delete() function.

Example

# 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()

Output

If we run the above code, it will display a list of items in the list box and a button to clear the Listbox.

Now, click the "Delete" button to clear the Listbox widget.

Updated on: 05-Aug-2021

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements