Rei*_*ica 11 python sorting treeview tkinter
有没有办法通过单击列对Tk Treeview中的条目进行排序?令人惊讶的是,我找不到任何文档/教程.
Rei*_*ica 20
patthoyts来自#tcl指出,TreeView的Tk的演示程序有排序功能.这是Python的等价物:
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))
[...]
Run Code Online (Sandbox Code Playgroud)
mad*_*ius 13
这在python3中不起作用.由于变量是通过引用传递的,因此所有lambdas最终都引用了列中相同的最后一个元素.
这对我有用:
for col in columns:
treeview.heading(col, text=col, command=lambda _col=col: \
treeview_sort_column(treeview, _col, False))
Run Code Online (Sandbox Code Playgroud)
madonius是对的,但是这里有完整的示例和正确的、易于理解的解释
Sridhar Ratnakumar提供的答案在 python3 中不起作用(显然在 python2.7 中也不起作用):由于变量是通过引用传递的,所以所有 lambda 最终都会引用列中相同的最后一个元素。
你只需要改变这个for loop:
for col in columns:
treeview.heading(col, text=col, command=lambda _col=col: \
treeview_sort_column(treeview, _col, False))
Run Code Online (Sandbox Code Playgroud)
并且必须将相同的更改应用于 treeview_sort_column 内的 lambda 函数
所以完整的解决方案如下所示:
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, text=col, command=lambda _col=col: \
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 _col=col: \
treeview_sort_column(treeview, _col, False))
[...]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10827 次 |
| 最近记录: |