Python Tkinter Treeview Sort Tree
based on examples and Henry's help I have come up with the following code to sort the tree in a tkinter treeview, but it does not work. I do not get any errors but the tree is not
Solution 1:
Since you are just adding the command to column #0
, you don't have to put it in a loop.
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
tree = ttk.Treeview(root,height=10)
tree.pack()
deftreeview_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) inenumerate(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 inrange(10):
tree.insert("",0,text=i)
root.mainloop()
Solution 2:
As I wanted to sort by column values alphabetically on clicking the specific column header I made an addition to the function in the answer of @Henry Yik and wanted to post for people with the same question in the future.
def treeview_sort_column(tv, col, reverse):
column_index = self.tree["columns"].index(col)
l = [(str(tv.item(k)["values"][column_index]), k) for k in tv.get_children()]
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))
Post a Comment for "Python Tkinter Treeview Sort Tree"