Tk treeview column sort

匿名 (未验证) 提交于 2019-12-03 01:56:01

问题:

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.

回答1:

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


回答2:

This did not work in python3. Since the Variable was passed by reference, all lambdas ended up refering to the same, last, element in columns.

This did the trick for me:

for col in columns:     treeview.heading(col, text=col, command=lambda _col=col: \                      treeview_sort_column(treeview, _col, False)) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!