Reputation: 1
I wrote a code to display a table using tkinter ttk Treeview. Then, I selected one of the item on the table, and made a change on its item. So, I updated the table by deleting all of its items and inserting a new ones. But why were the items still referring to old table's item added by new ones?
import tkinter as tk
from tkinter import ttk
win=tk.Tk()
def testcommand():
for i in tabel.get_children():
print(i)
for i in tabel.get_children():
tabel.delete(i)
for i in tes:
tabel.insert('', 'end', text=str(i))
for i in tabel.get_children():
print(i)
tabel=ttk.Treeview(win,selectmode='browse')
tabel.heading('#0',text="COBA")
tes=[1,2,3,4]
for i in tes:
tabel.insert('','end',text=str(i))
tabel.pack()
ttk.Button(win,text='Test',command=testcommand).pack()
win.mainloop()
In the first 'print' statement, I got ('I001','I002','I003','I004') items, but after I updated my treeview, the item continued to ('I005','I006','I007','I008').
Why the 'delete method' from treeview didn't reset the item back to 'I001'? Anyone can help me please?
Upvotes: 0
Views: 14013
Reputation: 16169
Tkinter default names for the items of a treeview are 'I001', 'I002', ... and the counter used to create the names is not reset when all items are deleted from the treeview.
If one wants to reset the item names, they have to explicitly name the items themselves when creating them:
tree.insert('', 'end', <name>, **kw)
Adapting the OP's code, it gives
import tkinter as tk
from tkinter import ttk
win=tk.Tk()
def testcommand():
for i in tabel.get_children():
print(i)
for i in tabel.get_children():
tabel.delete(i)
for i in tes:
tabel.insert('', 'end', 'item%i' % i, text=str(i)) # explicitly name the item
for i in tabel.get_children():
print(i)
tabel=ttk.Treeview(win,selectmode='browse')
tabel.heading('#0',text="COBA")
tes=[1,2,3,4]
for i in tes:
tabel.insert('','end', 'item%i' % i, text=str(i)) # explicitly name the item
tabel.pack()
ttk.Button(win,text='Test',command=testcommand).pack()
win.mainloop()
And the output when clicking on the test button is
item1
item2
item3
item4
item1
item2
item3
item4
as expected by the OP.
Upvotes: 2