排序ttk.treeview记录

时间:2019-03-13 12:24:54

标签: python sorting tkinter treeview

我是python的初学者,请帮助我如何在treeview中对行进行排序,我想从excel中读取数据并在treeview的排序列表中显示它们 现在它的输出就像我要按ID排序的照片

enter code here 
def show_data():
   wb = openpyxl.load_workbook('F:\python project\Form1.xlsx')
   sheet = wb.get_sheet_by_name('Sheet1')
   lb.delete(*lb.get_children())
   for row in sheet.iter_rows(min_row=1, min_col=0):
        lb.insert('', 'end', values=[cell.value for cell in row])
cols = ('name', 'ID', 'Mark')
lb=ttk.Treeview(frame1, columns=cols, show='headings')
for col in cols:
    lb.heading(col, text=col)
Button(frame2, text='show DB', command=show_data).grid(row=0, column=2, 
sticky=W, pady=4)

enter image description here

1 个答案:

答案 0 :(得分:0)

我很确定粘贴的链接已经有了答案,但是如果要排序的列是数字,则排序似乎是无序的。这是正确排序的方法。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

class MyTree(ttk.Treeview):
    def __init__(self,master,**kw):
        ttk.Treeview.__init__(self,master,**kw)
        header = ("ID", "Column 2","Column 3")
        width = (100,100,100)
        self["columns"] = header
        for i in range(len(header)):
            self.column(header[i], width=width[i], anchor="w")
            self.heading(header[i], text=header[i], anchor='w')

        self.heading("ID", text="ID", command=lambda _col="ID": self.tree_sort(self, _col, False))

    def tree_sort(self, tv, col, reverse):
        l = [(int(tv.set(k, col)), k) for k in tv.get_children('')]
        l.sort(reverse=reverse)

        for index, (val, k) in enumerate(l):
            tv.move(k, '', index)

        tv.heading(col, command=lambda: self.tree_sort(tv, col, not reverse))

tree = MyTree(root,height=20)
tree.pack()

for i in range(50):
    tree.insert("",0,text=f"Test{i}",values=(i,f"Test String {i}",f"Amount {i}"))

root.mainloop()