【发布时间】:2017-10-16 09:28:22
【问题描述】:
有没有办法在不按标题的情况下达到与这篇文章 python ttk treeview sort numbers 类似的结果?最好的方法是在插入项目之后。
【问题讨论】:
标签: python-3.x treeview ttk
有没有办法在不按标题的情况下达到与这篇文章 python ttk treeview sort numbers 类似的结果?最好的方法是在插入项目之后。
【问题讨论】:
标签: python-3.x treeview ttk
如果您要在每次插入新项目时对内容进行排序,那么更有效的方法是将项目插入正确的位置,而不是为每次插入对整个数据进行排序。
这是使用标准bisect 模块实现此目的的一种方法,其bisect(a, x) 函数为您提供x 应插入a 以保持顺序的索引(假设a 已排序)。在下面的示例中:
GUI;self.tree,只有一列;insert_item 方法在树中的某个类别下方插入一个新行(由location 指向),并且每个类别下的项目必须在我的应用程序中单独排序,这就是为什么我只检索该类别的孩子. from bisect import bisect
# ... class GUI contains the treeview self.tree ...
def insert_item(self, location, item_name, item_id):
"""Inserts a new item below the provided location in the treeview,
maintaining lexicographic order wrt names."""
contents = [
self.tree.item(child)["text"]
for child in self.tree.get_children(location)
]
self.tree.insert(
location, bisect(contents, item_name), item_id, text=item_name
)
【讨论】:
要在每次插入新项目后对 Treeview 进行排序,只需在代码中的正确位置添加对排序函数的显式调用即可。
示例代码:
import tkinter as tk
from tkinter import ttk
counter = 0
numbers = ['1', '10', '11', '2', '3', '4', '24', '12', '5']
def sort_treeview():
content = [(tv.set(child, column), child)
for child in tv.get_children('')]
try:
content.sort(key=lambda t: int(t[0]))
except:
content.sort()
for index, (val, child) in enumerate(content):
tv.move(child, '', index)
def add_item():
global counter
if counter < 8:
tv.insert('', 'end', values=numbers[counter])
counter += 1
# Sort the treeview after the new item was inserted
# -------------------------------------------------
sort_treeview()
root = tk.Tk()
column = 'number'
tv = ttk.Treeview(root, columns=column, show='headings')
tv.pack()
button = tk.Button(root, text='Add entry', command=add_item)
button.pack()
root.mainloop()
【讨论】: