【问题标题】:Python Tkinter Treeview - Iterating 'get_children' outputPython Tkinter Treeview - 迭代“get_children”输出
【发布时间】:2015-04-25 10:35:53
【问题描述】:

我正在尝试稍后遍历 Treeview 中的数据。然后我希望能够对其进行排序。

from tkinter import *
from tkinter.ttk import *
import pickle

root = Tk()

def treeData(event):
    children = tree.get_children()
    print(children)

entry = StringVar()
a = Entry(root, textvariable=entry)
a.grid(column=0,row=0)
a.bind("<Key>", function)

file_data = []
file = open('data.dat', 'rb')
while True:
    try:
        file_data.append(pickle.load(file))
    except EOFError:
        break
file.close()

column_names = ("Column 1", "Column 2")
tree = Treeview(root, columns=column_names)
tree['show'] = 'headings'
for x in file_data:
    a = tree.insert('', 'end', values=x)
for col in column_names: 
    tree.heading(col, text=col)

tree.grid(column=0, row=1)

在我 print(children) 时称为“treeData”的函数中,它会输出一个类似于此的列表 - ('I001', 'I002', 'I003', 'I004')

我希望有人知道如何将这些数据转换为 Treeview 行中实际显示的内容?

谢谢,

【问题讨论】:

  • 没有loans.dat 的示例或虚拟版本无济于事。

标签: python tkinter treeview children


【解决方案1】:

您的问题记录在官方 tkinter documentation for the Treeview widget 中。

get_children 方法返回一个项目 ID 列表,每个孩子一个。树视图的item 方法将返回给定项目的数据字典。因此,您可以使用以下方式迭代这些值:

for child in tree.get_children():
    print(tree.item(child)["values"])

【讨论】:

  • 据我了解,这里有趣的是I001I002 等是默认的iid 值,如果没有提供任何东西,Tkinter 会提供。现在,有趣的部分开始于某人(那是我)在填充树时使用列表索引的绝妙主意(似乎是一种避免将选定项目转换回它们起源的对象的麻烦的好方法)然后了解到项目 0 会返回 I001。可能 Tkinter 将为 iid 提供 0 视为不提供任何东西。至少这是我的猜测。
  • 另外,我认为如果你使用索引值(一个好主意......一开始!)会在以后导致淫秽的并发症。如果添加或删除项目,或者对列表进行排序,则 Iid=index 值将全部错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 2023-04-04
  • 1970-01-01
  • 2020-10-05
  • 2018-02-14
  • 2019-05-25
  • 2012-01-07
相关资源
最近更新 更多