Delete and Edit items in Tkinter TreeView

Tkinter Treeview widget is used to display the data in a hierarchical structure. In this structure, each row can represent a file or a directory. Each directory contains files or additional directories. If we want to create a Treeview widget, then we can use Treeview(parent, columns) constructor to build the table.

The Treeview widget items can be edited and deleted by selecting the item using tree.selection() function. Once an item is selected, we can perform certain operations to delete or edit the item.


# 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

# Create an instance of Style widget
style = ttk.Style()

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

# 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', 'Wolkswagon'))
tree.insert('', 'end', text="5", values=('5', 'Tata Motors'))
tree.insert('', 'end', text="6", values=('6', 'Renault'))


def edit():
   # Get selected item to Edit
   selected_item = tree.selection()[0]
   tree.item(selected_item, text="blub", values=("foo", "bar"))

def delete():
   # Get selected item to Delete
   selected_item = tree.selection()[0]

# Add Buttons to Edit and Delete the Treeview items
edit_btn = ttk.Button(win, text="Edit", command=edit)
del_btn = ttk.Button(win, text="Delete", command=delete)



Executing the above code will display a window that contains a list of car models and ID in it.

If we select a particular row and press edit or delete button, then it will perform the operations defined in the program.

Select the 4th row and click the "Delete" button.

It will produce the following output −

Updated on: 18-Jun-2021

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started