list.sort
method, sorted
function accept optional key
parameter. The return value of the function is used as comparison key.
Specifying key
function that convert the treeview item into number will solve your problem.
Example:
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…