添加 tkinter 后在树视图中对项目进行排序 [英] Sorting items in treeview after adding tkinter

查看:124
本文介绍了添加 tkinter 后在树视图中对项目进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于将行插入树后按字母顺序排序的问题.我试图通过添加或排序(数据)来添加方法 data.sort() 但它没有用.或者有什么办法可以一键按字母顺序排序项目?

I've got a question about alphabetically sorting rows after inserting them to tree. I tried to add method data.sort() by adding or sorted(data) but it didnt work. Or is there any way to sort alphabetically items with one click button?

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Medicine database")

def add():
    data = tree.insert("",END,values=("",e1.get()))
    data.sort()
    or sorted(data)
Or:
def sort():
    for i in tree.getchildren():
        tree.item(sorted(item))['values']

e1=Entry(root,width=15)
e1.grid(row=0,column=1,padx=10,pady=10,sticky=E,rowspan=1)

btn1 = Button(root,text="add",width=10,command=add)
btn1.grid(row =1,column=0,padx=10,pady=10,rowspan=2)


#treeview
tree = ttk.Treeview(root,height=25)
tree["columns"]=("one","two","three","four")
tree.column("one",width=120)
tree.column("two",width=160)
tree.column("three",width=130)
tree.column("four",width=160)
tree.heading("one", text="Numer seryjny leku")
tree.heading("two", text="Nazwa Leku")
tree.heading("three", text="Ampułki/Tabletki")
tree.heading("four",text="Data ważności")
tree["show"]="headings"
tree.grid(row=0,column=2,rowspan=6,pady=20)

root.geometry("840x580")
root.mainloop()

推荐答案

对 treeview 进行排序的方式如下:

Sorting a treeview is done the following way:

  1. 从列表中的所有行中收集数据.
  2. 对列表进行排序.
  3. 将树视图中的项目移动到与列表中相同的顺序.

根据 python ttk treeview sort numbers 的答案改编代码,这给出:

Adapting the code from the answers of python ttk treeview sort numbers, this gives:

def sort():
    rows = [(tree.item(item, 'values'), item) for item in tree.get_children('')]
    # if you want to sort according to a single column:
    # rows = [(tree.set(item, column), item) for item in tree.get_children('')]
    rows.sort()

    # rearrange items in sorted positions
    for index, (values, item) in enumerate(rows):
        tree.move(item, '', index)

只需将 sort() 函数用作按钮命令即可对树视图进行排序.

Just use the sort() function as a button's command to sort the treeview.

根据列二"中的值按字母顺序对行进行排序,而不考虑大小写:

To sort alphabetically rows according to the value in column 'two' and regardless of capitalization:

def sort():
    rows = [(tree.set(item, 'two').lower(), item) for item in tree.get_children('')]
    rows.sort()

    for index, (values, item) in enumerate(rows):
        tree.move(item, '', index)

这篇关于添加 tkinter 后在树视图中对项目进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆