I want to delete a single row in a TreeView
in Tkinter.
I know that this method:
def delButton(self):
x = main.tree.get_children()
for item in x:
main.tree.delete(item)
deletes the whole tree. But I want to delete only one row. How can I do this?
Moreover, I want to know how to edit a TreeView
row as well.
You are not deleting the whole tree you are just deleting all children from the root item, because you use delete for each item in your iteration.
You can use a if
statement to determine which item you want, or you can get the selected item with selected_item = tree.selection()[0]
and delete it. With the .item()
method you can full access to the item for modification. Example:
from Tkinter import Tk, Button
import ttk
root = Tk()
tree = ttk.Treeview(root)
tree["columns"]=("one","two")
tree.column("one", width=100 )
tree.column("two", width=100)
tree.heading("one", text="coulmn A")
tree.heading("two", text="column B")
tree.insert("" , 0, text="Line 1", values=("1A","1b"))
id2 = tree.insert("", 1, "dir2", text="Dir 2")
tree.insert(id2, "end", "dir 2", text="sub dir 2", values=("2A","2B"))
##alternatively:
tree.insert("", 3, "dir3", text="Dir 3")
tree.insert("dir3", 3, text=" sub dir 3",values=("3A"," 3B"))
def edit():
x = tree.get_children()
for item in x: ## Changing all children from root item
tree.item(item, text="blub", values=("foo", "bar"))
def delete():
selected_item = tree.selection()[0] ## get selected item
tree.delete(selected_item)
tree.pack()
button_del = Button(root, text="del", command=delete)
button_del.pack()
button_del = Button(root, text="edit", command=edit)
button_del.pack()
root.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With