添加 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:
- 从列表中的所有行中收集数据.
- 对列表进行排序.
- 将树视图中的项目移动到与列表中相同的顺序.
根据 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)