python ttk treeview排序数字

标签 python sorting tkinter treeview ttk

我正在尝试使用这个问题 (Tk treeview column sort) 的答案中说明的 ttk.Treeview 排序函数,它适用于像“abc”、“bcd”、“cde”等字符串,但是当我尝试对数字进行排序时,它最终显示如下:

1
10
11
2
3
...

我希望对数据进行排序,使得输出为:

1
2
3
...
10
11

我知道 TreeView 列中的值是字符串,我很可能需要在排序前将它们转换为整数,但我不知道该怎么做。

最佳答案

list.sort方法,sorted函数接受可选的 key 参数。函数的返回值作为比较键。

指定将 TreeView 项目转换为数字的 key 函数将解决您的问题。

例子:

try:
    from tkinter import *
    from tkinter import ttk
except ImportError:
    from Tkinter import *
    import ttk

def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]
    l.sort(key=lambda t: int(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))

root = Tk()
columns = ('number',)
treeview = ttk.Treeview(root, columns=columns, show='headings')
for t in ('1', '10', '11', '2', '3'):
    treeview.insert('', END, values=(t,))
treeview.pack()
for col in columns:
    treeview.heading(col, text=col,
                     command=lambda c=col: treeview_sort_column(treeview, c, False))

mainloop()

enter image description here

关于python ttk treeview排序数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22032152/

相关文章:

python - 如何在 python Tkinter 中更新字典的值

python - 在 Tkinter 中为框架添加标签会忽略框架的属性

python - "is"运算符对整数的行为异常

python - 高效的 Matplotlib 重绘

c++ - 对存储在双端队列中的类对象进行排序

python - 如何制作一个背景颜色为用户选择的颜色的标签?

python - 导入 h5py 时出错

python - 如何使用 Numba 作为可选依赖项分发 Python 包

java - 如何排序和保留 web 服务的结果?

ios - 按日期使用自定义类对 NSMutableArray 进行排序