python ttkツリービューソート番号
質問
私はttkを使用しようとしています。この質問への回答に示されているツリービューソート関数(Tkツリービュー列のソート)そして、'abc'、'bcd'、'cde'などの文字列ではうまく動作します。、しかし、私は数字をソートしようとすると、それはこのように表示されてしまいます:
1
10
11
2
3
...
出力が次のようにソートされるようにデータをソートしたいと思います:
1
2
3
...
10
11
Treeview列の値は文字列であり、ソートする前に整数に変換する必要がある可能性が最も高いことは知っていますが、その方法を理解できません。
解決
list.sort
メソッド, sorted
機能は任意受け入れます key
パラメータ。関数の戻り値は比較キーとして使用されます。
指定 key
treeview項目を数値に変換する関数は、問題を解決します。
例を示します。:
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()
他のヒント
I figure I'd add this bit of code for anyone wanting to use the above solution for both regular string sorts and numeric sorts.
def treeview_sort_column(tv, col, reverse):
l = [(tv.set(k, col), k) for k in tv.get_children('')]
try:
l.sort(key=lambda t: int(t[0]), reverse=reverse)
# ^^^^^^^^^^^^^^^^^^^^^^^
except ValueError:
l.sort(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))
It took me a while to find a variant of this answer, but I thought I would post an answer for those looking to sort dates as a string (i.e. 'DD/MM/YYYY')
import datetime
def treeview_sort_column(tv, col, reverse):
l = [(tv.set(k, col), k) for k in tv.get_children('')]
l.sort(key=lambda: x, datetime.datetime.strptime(x[0], '%d/%m/%y'), 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))
所属していません StackOverflow