sam*_*tun 9 python tree row tkinter
我只是从python 3.4中的一个小tkinter树程序开始.
我坚持返回所选行的第一个值.我有多行有4列,我在左键单击一个项目时调用一个函数:
tree.bind('<Button-1>', selectItem)
Run Code Online (Sandbox Code Playgroud)
功能:
def selectItem(a):
curItem = tree.focus()
print(curItem, a)
Run Code Online (Sandbox Code Playgroud)
这给了我这样的东西:
I003 <tkinter.Event object at 0x0179D130>
Run Code Online (Sandbox Code Playgroud)
看起来所选项目已正确识别.我现在需要的是如何获得行中的第一个值.
树创作:
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()
Run Code Online (Sandbox Code Playgroud)
tob*_*s_k 27
要获取所选项及其所有属性和值,可以使用以下item方法:
def selectItem(a):
curItem = tree.focus()
print tree.item(curItem)
Run Code Online (Sandbox Code Playgroud)
这将输出一个字典,然后您可以从中轻松检索单个值:
{'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''}
Run Code Online (Sandbox Code Playgroud)
另外请注意,回调将被执行之前,在树中的焦点变了,即你将获得该项目是您点击的新项目之前选择.解决此问题的一种方法是使用事件类型ButtonRelease.
tree.bind('<ButtonRelease-1>', selectItem)
Run Code Online (Sandbox Code Playgroud)