[英]Python 3.3.2 tkinter ttk TreeView per-column sorting only sorts by last column?
我試圖得到一個簡單的ttk TreeView表,使用標題'command'標簽進行每列排序,但它似乎不正常。 我正在使用這個問題的答案來實現功能: Tk treeview列排序
我的代碼:
import tkinter as tk
from tkinter import ttk
def treeview_sort_column(tv, col, reverse):
print('sorting %s!' % col)
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):
print('Moving Index:%r, Value:%r, k:%r' % (index, val, k))
tv.move(k, '', index)
# reverse sort next time
tv.heading(col, command=lambda: treeview_sort_column(tv, col, not reverse))
cols = ('name', 'path', 'time', 'pb')
root = tk.Tk()
root.geometry("700x500")
listbox = ttk.Treeview(root, columns=cols, show="headings")
for each in ('name', 'path', 'time','pb'):
listbox.heading(each,text=each.capitalize(),command=lambda: treeview_sort_column(listbox, each, False))
listbox.column( each, width=tk.font.Font().measure(each.title() ))
if not each == 'path':
listbox.column(each,stretch=False)
if not each == 'name':
listbox.column( each, anchor='center')
listbox.pack(expand=True, fill=tk.BOTH)
root.mainloop()
我遇到的問題是每次我運行它時,它只按最后一列排序,而不是按你點擊的列排序(用treeview_sort_column函數中的print語句驗證)。 單擊結果窗口中的任何列得到的輸出:
sorting pb!
sorting pb!
sorting pb!
sorting pb!
sorting pb!
sorting pb!
sorting pb!
sorting pb!
如果我通過在循環之后添加它來從for循環中的每個命令的動態創建變為顯式循環,那么它按預期工作(即每個列自行排序)。
listbox.heading('name', command=lambda: treeview_sort_column(listbox, 'name', False))
listbox.heading('path', command=lambda: treeview_sort_column(listbox, 'path', False))
listbox.heading('time', command=lambda: treeview_sort_column(listbox, 'time', False))
listbox.heading('pb', command=lambda: treeview_sort_column(listbox, 'pb', False))
生產:
sorting name!
sorting name!
sorting path!
sorting path!
sorting time!
sorting time!
sorting pb!
sorting pb!
顯然這是一個非常簡單的例子,我的最終應用程序實際上將數據插入列中(也有更多列),但由於我甚至無法使這個簡化版本工作,我很茫然。 我的循環有什么問題導致lambda函數搞砸了?
我的系統:
你應該以其他方式使用lambda。 在你的代碼中,每個lambda都獲得一個指向同一個變量的指針,這就是為什么所有函數都做同樣的事情。 例如,您應該復制變量以使lambda唯一。 如何做到的一個例子:
for each in ('name', 'path', 'time','pb'):
listbox.heading(each,text=each.capitalize(),command=lambda each_=each: treeview_sort_column(listbox, each_, False))
簡單的例子:
funcs = []
for item in ('abc', 'def', 'ghi'):
funcs.append(lambda : print(item))
for f in funcs:
f()
它打印:
ghi
ghi
ghi
但是具有固定lambda的版本:
funcs = []
for item in ('abc', 'def', 'ghi'):
funcs.append(lambda item_=item: print(item_))
for f in funcs:
f()
版畫
abc
def
ghi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.