python tkinter treeview排序树

时间:2019-03-20 19:16:55

标签: python sorting tkinter

基于示例和亨利的帮助,我想出了以下代码在tkinter树视图中对树进行排序,但它不起作用。 我没有收到任何错误,但树未排序。 任何帮助表示赞赏。

def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]
    l.sort(key=lambda t: int(t[0]), reverse=reverse)
    #      ^^^^^^^^^^^^^^^^^^^^^^^

    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)

    tv.heading(col,
               command=lambda: treeview_sort_column(tv, col, not reverse))


def SortTree():

    columns = ('#0',)

    for col in columns:
        tree.heading(col, text=col,
                         command=lambda c=col: treeview_sort_column(tree, c, False))

1 个答案:

答案 0 :(得分:0)

由于您只是将命令添加到列#0中,因此不必将其放入循环中。

from tkinter import ttk
import tkinter as tk

root = tk.Tk()
tree = ttk.Treeview(root,height=10)
tree.pack()

def treeview_sort_column(tv, col, reverse):
    l = [(tv.item(k)["text"], k) for k in tv.get_children()] #Display column #0 cannot be set
    l.sort(key=lambda t: t[0], reverse=reverse)

    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)

    tv.heading(col, command=lambda: treeview_sort_column(tv, col, not reverse))

tree.heading("#0", command=lambda : treeview_sort_column(tree, "#0", False))

for i in range(10):
    tree.insert("",0,text=i)

root.mainloop()