This must be something simple I'm missing, but I can't seem to figure out how to set the selection row in a Treeview using the selection_set method. I am confused by the ttk documentation which sometimes refers to items and other times to iid for method arguments. When I insert a row into the Treeview, am I not creating an item which I give the handle iid?
import Tkinter as Tk
import ttk
root = Tk.Tk()
tree = ttk.Treeview(root, displaycolumns='#all')
tree["columns"]=("1", "2", "3", "4")
tree.column("#0", width=70)
tree.column("1", width=70, anchor=Tk.CENTER)
tree.column("2", width=50, anchor=Tk.CENTER)
tree.column("3", width=50, anchor=Tk.CENTER)
tree.column("4", width=70, anchor=Tk.CENTER)
tree.heading("1", text="Column 1")
tree.heading("2", text="Column 2")
tree.heading("3", text="Column 3")
tree.heading("4", text="Column 4")
id2 = []
count = 0
item_list = ['A', 'B', 'C', 'D']
for item in item_list:
id = tree.insert("", count, iid='Row %s'%count, text=item, values=('1', '2', '3', '4'))
id2.append(id)
count += 1
tree.selection_set('Row 0') # Doesn't work -- returns "_tkinter.TclError: Item Row not found"
tree.pack(fill=Tk.BOTH, expand=1, side=Tk.RIGHT,padx=50)
Tk.mainloop()
Traceback:
Traceback (most recent call last):
File "python-ttk-treeview-how-to-select-a-row.py", line 28, in <module>
tree.selection_set('Row 0') # Doesn't work -- returns "_tkinter.TclError: Item Row not found"
File "C:\Python\lib\lib-tk\ttk.py", line 1402, in selection_set
self.selection("set", items)
File "C:\Python\lib\lib-tk\ttk.py", line 1397, in selection
return self.tk.call(self._w, "selection", selop, items)
_tkinter.TclError: Item Row not found
It's because you have spaces embedded in the selection name. According to the answer to this related question you can use names like that simply by putting quotes around them:
tree.selection_set('"Row 0"') # Does work.
The clue was in the error message said Item Row not found not Item Row 0 not found.
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