Tkinter Treeview Delete Item
The selected item can be deleted in the Treeview control using the delete() method, which is illustrated with an example below.
Example#1
Delete the selected item. This program sets selectmode=EXTENDED when creating the Treeview control, which is equivalent to multiple selections at once. The second option can be selected discontinuously if you press the Ctrl key at the same time when clicking the mouse. If the second option is selected by pressing the Shift key at the same time as clicking the mouse, you can select consecutive options. There is a Remove button at the bottom of this program, click this button to delete the selected item.
from tkinter import *
from tkinter.ttk import *
def removeItem():
iids = tree.selection()
for iid in iids:
tree.delete(iid)
root = Tk()
root.title("apidemos.com")
stateCity = {"Illinois": "Chicago", "California": "Los Angeles",
"Texas": "Houston", "Washington": "Seattle",
"Jiangsu": "Nanjing", "Shandong": "Qingdao",
"Guangdong": "Guangzhou", "Fujian": "Xiamen"}
# Create a Treeview with multiple selections selectmode=EXTENDED
tree = Treeview(root,columns=("cities"),selectmode=EXTENDED)
# Create column headings
tree.heading("#0",text="State")
tree.heading("cities",text="City")
# Format field
tree.column("cities",anchor=CENTER)
# Create content
for state in stateCity.keys():
tree.insert("",index=END,text=state,values=stateCity[state])
tree.pack()
rmBtn = Button(root,text="Remove",command=removeItem)
rmBtn.pack(pady=5)
root.mainloop()
Output:
The above program executes the removeItem( ) method in lines 4 to 7 when the Remove button is clicked, and then line 5 is executed first as shown below.
iids = tree.selection()
The above method will pass the current options to iids, whose data type is tuple, so lines 6 and 7 are loops that can traverse this tuple and then delete the selected items in turn.