python tkinter树获取选定的项目值 [英] python tkinter tree get selected item values

查看:55
本文介绍了python tkinter树获取选定的项目值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm just starting with a small tkinter tree program in python 3.4.

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

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:

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

功能:

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

这给了我这样的东西:

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.

树创建:

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 方法:

To get the selected item and all its attributes and values, you can use the item method:

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': ''}

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

Also note that the callback will be executed before the focus in the tree changed, i.e. you will get the item that was selected before you clicked the new item. One way to solve this is to use the event type ButtonRelease instead.

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

这篇关于python tkinter树获取选定的项目值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆