How to clear an entire Treeview with Tkinter?

TkinterPythonServer Side ProgrammingProgramming

Tkinter Treeview widgets are used to display the hierarchy of the items in the form of a list. It generally looks like the file explorer in Windows or Mac OS.

Let us suppose we have created a list of items using treeview widget and we want to clear the entire treeview, then we can use the delete() function. The function can be invoked while iterating over the treeview items.

Example

In this example, we will create a treeview for the Programming Language and will clear the list of items using delete() operation.

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

#Create an instance of tkinter frame
win = Tk()
win.title("Application to represent the Programming Languages ")

#Set the geometry
win.geometry("600x200")

#Create a label
ttk.Label(win, text ="Treeview(hierarchical)").pack()

#Treeview List Instantiation
treeview = ttk.Treeview(win)
treeview.pack()
treeview.insert('', '0', 'i1', text ='Language')
treeview.insert('', '1', 'i2', text ='FrontEnd')
treeview.insert('', '2', 'i3', text ='Backend')
treeview.insert('i2', 'end', 'HTML', text ='RUBY')
treeview.insert('i2', 'end', 'Python', text ='JavaScript')
treeview.insert('i3', 'end', 'C++', text ='Java')
treeview.insert('i3', 'end', 'RUST', text ='Python')
treeview.move('i2', 'i1', 'end')
treeview.move('i3', 'i1', 'end')
treeview.move('i2', 'i1', 'end')

win.mainloop()

Running the above code will display a window that contains a treeview hierarchy of Programming languages categorized for FrontEnd and Backend.

Now, adding the following code before the mainloop will remove and clear the whole treeview list.

#Clear the treeview list items
for item in treeview.get_children():
   treeview.delete(item)

Output

After invoking the function, it will clear the whole treeview list items from the window.

After clearing the treeview, it will display an empty treeview list.

raja
Published on 26-Mar-2021 11:10:36
Advertisements