Qubit1028 Qubit1028 - 1 year ago 398
Python Question

ttk Treeview: How to select a row?

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

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'))
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)



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

Answer Source

It's because you have spaces embedded in the selection name. According to the answer to this question you can only do that by using something like this:

tree.selection_set('"Row 0"')  # Does work

The clue was the error message which said Item Row not found not Item Row 0 not found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download