python-3.x 在Tkinter Treeview中,如何对特定列进行降序排序?[副本]

zi8p0yeb  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(138)

此问题已在此处有答案

Tk treeview column sort(6个回答)
11天前关闭
如何按降序(9,7,5,4,3,1)对Badge列编号进行排序?当然,通过对Badge数字排序,行的顺序也会改变。我想得到:

5,"Frank","9"
3,"Daniel","7"
4,"Leonard","5"
1,"Jack","4"
6,"Robert","3"
2,"Tom","1"

我在网上找到了一些例子,但我无法将它们应用到我的代码中。你能用我的代码告诉我解决方案吗?
代码:

from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws['bg']='#fb0'

data  = [
    [1,"Jack","4"],
    [2,"Tom","1"],
    [3,"Daniel","7"],
    [4,"Leonard","5"],
    [5,"Frank","9"],
    [6,"Robert","3"],
    ]

tv = ttk.Treeview(ws)
tv['columns']=('Rank', 'Name', 'Badge')
tv.column('#0', width=0, stretch=NO)
tv.column('Rank', anchor=CENTER, width=80)
tv.column('Name', anchor=CENTER, width=80)
tv.column('Badge', anchor=CENTER, width=80)
tv.heading('#0', text='', anchor=CENTER)
tv.heading('Rank', text='Id', anchor=CENTER)
tv.heading('Name', text='rank', anchor=CENTER)
tv.heading('Badge', text='Badge', anchor=CENTER)
tv.pack()

def func1():
    for record in data:
        Rank = record[0]
        Name = record[1]
        Badge = record[2]
        
        datagrid = [Rank, Name, Badge]

        tv.insert(parent='', index='end', values=(datagrid))

button = Button(ws, text="Button", command = func1)
button.place(x=1, y=1)

ws.mainloop()
csga3l58

csga3l581#

from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws['bg']='#fb0'

data  = [
    [1,"Jack","4"],
    [2,"Tom","1"],
    [3,"Daniel","7"],
    [4,"Leonard","5"],
    [5,"Frank","9"],
    [6,"Robert","3"],
    ]

tv = ttk.Treeview(ws)
tv['columns']=('Rank', 'Name', 'Badge')
tv.column('#0', width=0, stretch=NO)
tv.column('Rank', anchor=CENTER, width=80)
tv.column('Name', anchor=CENTER, width=80)
tv.column('Badge', anchor=CENTER, width=80)
tv.heading('#0', text='', anchor=CENTER)
tv.heading('Rank', text='Id', anchor=CENTER)
tv.heading('Name', text='rank', anchor=CENTER)
tv.heading('Badge', text='Badge', anchor=CENTER, command=lambda: sort_treeview(tv, "Badge", False))
tv.pack()
def sort_treeview(tv, col, descending):
    

    data = [(tv.set(item, col), item) for item in tv.get_children('')]
    data.sort(reverse=descending)
    
    for index, item in enumerate(data):
        tv.move(item[1], '', index)
        print(item)
    tv.heading(col, command=lambda: sort_treeview(tv, col, not descending))

def func1():
    for record in data:
        Rank = record[0]
        Name = record[1]
        Badge = record[2]
        
        datagrid = [Rank, Name, Badge]

        tv.insert(parent='', index='end', values=(datagrid))

button = Button(ws, text="Button", command = func1)
button.place(x=1, y=1)

ws.mainloop()

相关问题