How to clear items from a ttk.Treeview widget?

TkinterPythonGUI-Programming

Generally, Tkinter treeview widget is used to draft or construct tables for the given data points in the input. We can even add items in the treeview widget to maintain a nested list in an application. If we want to remove or clear all the items in a given treeview widget, then we have to first select all the items present in the treeview widget using get_children() method.

Once we have selected all the treeview items programmatically, then we can delete the items using delete(item) method. In order to get all the children, we can use the delete() method inside a loop.

Example

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win= Tk()

# Set the size of the tkinter window
win.geometry("700x350")
s = ttk.Style()
s.theme_use('clam')

# Define a function to clear all the items present in Treeview
def clear_all():
   for item in tree.get_children():
      tree.delete(item)

# Add a Treeview widget
tree= ttk.Treeview(win, column=("c1", "c2"), show= 'headings', height= 6)
tree.column("# 1",anchor=CENTER)
tree.heading("# 1", text= "ID")
tree.column("# 2", anchor= CENTER)
tree.heading("# 2", text= "FName")

# Insert the data in Treeview widget
tree.insert('', 'end',text= "1",values=('1','Honda'))
tree.insert('', 'end',text= "2",values=('2', 'Hyundai'))
tree.insert('', 'end',text= "3",values=('3', 'Tesla'))
tree.insert('', 'end',text= "4",values=('4', 'Volkswagen'))
tree.insert('', 'end',text= "5",values=('5', 'Tata'))
tree.insert('', 'end',text= "6",values=('6', 'Renault'))

tree.pack()

# Create a Button for clearing the Treeview Item
ttk.Button(win, text= "Clear", command= clear_all).pack(pady=10)

win.mainloop()

Output

When we run the above code, it will display a window that contains a table and a Button widget.

Once we click the button, it will clear all the content of the treeview widget.

raja
Published on 08-Jun-2021 10:00:06
Advertisements