Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tk treeview column sort

Is there a way to sort the entries in a Tk Treeview by clicking the column? Surprisingly, I could not find any documentation/tutorial for this.

like image 828
Sridhar Ratnakumar Avatar asked Dec 27 '09 20:12

Sridhar Ratnakumar


1 Answers

patthoyts from #tcl pointed out that the TreeView Tk demo program had the sort functionality. Here's the Python equivalent of it:

def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]
    l.sort(reverse=reverse)

    # rearrange items in sorted positions
    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)

    # reverse sort next time
    tv.heading(col, command=lambda: \
               treeview_sort_column(tv, col, not reverse))

[...]
columns = ('name', 'age')
treeview = ttk.TreeView(root, columns=columns, show='headings')
for col in columns:
    treeview.heading(col, text=col, command=lambda: \
                     treeview_sort_column(treeview, col, False))
[...]
like image 138
Sridhar Ratnakumar Avatar answered Oct 06 '22 05:10

Sridhar Ratnakumar