Adam Davis
Adam Davis

Reputation: 31

Tkinter Treeview Column Sorting

Is there a way to sort the records in a Tk Treeview by clicking the column?

I have a Treeview database table displayed in a Tkinter module. The database is linked to a SQLite database where the data is sourced.

Upvotes: 2

Views: 4388

Answers (1)

toomanykyles
toomanykyles

Reputation: 21

@Mayur had the right idea, just missed including the definition of treeview_sort_column. I can vouch for the technique, though I implemented the call differently than the command option. You can review it at this link as well (though it may die in the future)

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))
[...]

Upvotes: 2

Related Questions