python - tkinter TreeView : get selected item values

标签 python tkinter tree treeview row

我刚开始使用 python 3.4 中的一个小型 tkinter 树程序。

我坚持返回所选行的第一个值。 我有多行,有 4 列,我在左键单击一个项目时调用了一个函数:

tree.bind('<Button-1>', selectItem)

函数:

def selectItem(a):
    curItem = tree.focus()
    print(curItem, a)

这给了我这样的东西:

I003 <tkinter.Event object at 0x0179D130>

看起来所选项目已被正确识别。 我现在需要的是如何获取行中的第一个值。

树的创建:

from tkinter import *
from tkinter import ttk

def selectItem():
    pass

root = Tk()
tree = ttk.Treeview(root, columns=("size", "modified"))
tree["columns"] = ("date", "time", "loc")

tree.column("date", width=65)
tree.column("time", width=40)
tree.column("loc", width=100)

tree.heading("date", text="Date")
tree.heading("time", text="Time")
tree.heading("loc", text="Loc")
tree.bind('<Button-1>', selectItem)

tree.insert("","end",text = "Name",values = ("Date","Time","Loc"))

tree.grid()
root.mainloop()

最佳答案

要获取所选项目及其所有属性和值,可以使用item 方法:

def selectItem(a):
    curItem = tree.focus()
    print tree.item(curItem)

这将输出一个字典,然后您可以从中轻松检索各个值:

{'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''}

另请注意,回调将在树中的焦点更改之前执行,即您将获得在单击新项目之前选中的项目。解决此问题的一种方法是改用事件类型 ButtonRelease

tree.bind('<ButtonRelease-1>', selectItem)

关于python - tkinter TreeView : get selected item values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614279/

相关文章:

c - 具有多个子节点和下一个节点的树

python, x = """"""; 被词法化为三重引号或 3 对引号

python - 使用类绘制星形?

python - 使用线程将 stdout 重定向到 Tkinter 文本小部件的问题

algorithm - 如果我们知道输入是按字母顺序排列的,我们如何优化 trie 的创建?

c# - 如何将有向无环图 (DAG) 转换为树

python - Google App Engine 中的数据存储

python - 仅使用字典 Python 3 计算 .txt 文件中的词频

python - dataframe和csv文件的日期格式可以相同吗?

python - 如何在类的 __init__ 函数中使用 Canvas 参数?