这一定是我想要的简单,但我似乎无法弄清楚如何使用selection_set
方法在Treeview中设置选择行。我对ttk文档感到困惑,该文档有时会引用" 项目"和其他时间到" iid "用于方法参数。当我在Treeview中插入一行时,我是不是创建了一个我给出句柄 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 (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
答案 0 :(得分:4)
这是因为您在选择名称中嵌入了空格。根据{{3}}的答案,你只能通过使用这样的东西来做到这一点:
tree.selection_set('"Row 0"') # Does work
线索是错误消息,其中Item Row not found
而非Item Row 0 not found
。