python - ttk TreeView : How to select a row?

标签 python treeview

<分区>

这一定是我所缺少的简单内容,但我似乎无法弄清楚如何使用 selection_set 方法在 Treeview 中设置选择行。我对 ttk 文档感到困惑,它有时引用 items 有时引用 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

最佳答案

这是因为您在选择名称中嵌入了空格。根据这个related question的回答您可以简单地通过在它们周围加上引号来使用这样的名称:

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

线索在错误消息中说 Item Row not found not Item Row 0 not found

关于python - ttk TreeView : How to select a row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28686238/

相关文章:

html - 我如何返回、转发和打印来自 my.resorces - vb.net 的(本地)WebBrowser1.DocumentText html 页面

c++ - 为 QML TreeView 创建模型

delphi - 高级自定义DrawItem时如何绘制TreeView样式选择矩形?

python - 使用 pd.to_datetime 处理多种日期时间格式

python - 如何为 Python matplotlib.animation 添加随时间变化的标题?

python - 使用 BeautifulSoup 抓取网站以下载其上的所有文档会抛出 IOError

java - 使用 (getClass().getResourceAsStream ("Path/to/pic")) 与 ("Path/to/pic") 的新图像实例

python - 尝试修复 SQL 语法中的错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法

python - 将两个列表组合在字典中 - python

vb.net - 动态 TreeView 高度