python tkinter树获取选定项值

2024-10-05 14:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是从Python3.4中的一个小tkinter树程序开始。

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

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

Tags: texttreedatetimebindtkinterdefcolumn
1条回答
网友
1楼 · 发布于 2024-10-05 14:26:21

要获取选定项及其所有属性和值,可以使用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)

相关问题 更多 >