python tkinter树获取选定的项目值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30614279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python tkinter tree get selected item values
提问by samtun
I'm just starting with a small tkinter tree program in python 3.4.
我只是从 python 3.4 中的一个小的 tkinter 树程序开始。
I'm stuck with returning the first value of the row selected. I have multiple rows with 4 columns and I am calling an a function on left-click on a item:
我坚持返回 selected 行的第一个值。我有 4 列的多行,我在左键单击一个项目时调用一个函数:
tree.bind('<Button-1>', selectItem)
The function:
功能:
def selectItem(a):
curItem = tree.focus()
print(curItem, a)
This gives me something like this:
这给了我这样的东西:
I003 <tkinter.Event object at 0x0179D130>
It looks like the selected item gets identified correctly. All I need now is how to get the first value in the row.
看起来所选项目已被正确识别。我现在需要的是如何获取行中的第一个值。
tree-creation:
树创建:
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()
采纳答案by tobias_k
To get the selected item and all its attributes and values, you can use the item
method:
要获取所选项目及其所有属性和值,您可以使用以下item
方法:
def selectItem(a):
curItem = tree.focus()
print tree.item(curItem)
This will output a dictionary, from which you can then easily retrieve individual values:
这将输出一个字典,然后您可以轻松地从中检索单个值:
{'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''}
Also note that the callback will be executed beforethe focus in the tree changed, i.e. you will get the item that wasselected before you clicked the new item. One way to solve this is to use the event type ButtonRelease
instead.
另外请注意,回调将被执行之前,在树中的焦点变了,即你将获得该项目是您点击的新项目之前选择。解决此问题的一种方法是改用事件类型ButtonRelease
。
tree.bind('<ButtonRelease-1>', selectItem)