Reputation: 6711
When using the Ttk Treeview control, I am getting a TclError when trying to programmatically set multiple selected items.
What is the correct way to set multiple items as selected in a Treeview control?
The documentation isn't clear about what types are allowed for items
:
selection_set(items)
items becomes the new selection.
I've simplified my code to the following:
try: # python 2
import Tkinter as tk
import ttk
except ImportError: # python 3
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
for text in ['apple', 'banana', 'coconut']:
tree.insert('', 'end', text=text)
all_items = list(tree.get_children())
print("all_items = {!r}".format(all_items))
tree.selection_set(all_items)
However, it raises an exception:
all_items = ['I001', 'I002', 'I003']
Traceback (most recent call last):
File ...
tree.selection_set(all_items)
File "C:\Python27\lib\lib-tk\ttk.py", line 1402, in selection_set
self.selection("set", items)
File "C:\Python27\lib\lib-tk\ttk.py", line 1397, in selection
return self.tk.call(self._w, "selection", selop, items)
_tkinter.TclError: Item ['I001', not found
The last line of the error message makes it seem like it is converting the list of items to a string just using str, but the format isn't what is expected by the backend.
Upvotes: 2
Views: 1619
Reputation: 6711
It turns out that the items
argument to selection_set
cannot be a list. It must be either a space-separated list of iids or a tuple of iids.
Either of the following worked for me:
tree.selection_set(tuple(all_items))
Or:
tree.selection_set(" ".join(all_items))
The latter method would not work if the item IDs were set using strings with spaces, however.
(Also, tree.get_children()
returns a tuple, so the conversion to list in the original code could also be removed and it would work. In my full code, I was generating the list in a more complicated way, though).
Upvotes: 2