如何在Python的Treeview控件中插入字典类型的数据
解决方案
问题点
代码调用ttk.Treeview的insert方法时直接传入了字典对象,该方法的values参数要求接收按列顺序排列的值序列,不会自动匹配列名从字典中提取对应值,因此无法正常显示数据。
修复后完整代码
from tkinter import * from tkinter import ttk class sales: def __init__(self,root): self.root=root self.root.geometry("%dx%d+0+0" % (self.root.winfo_screenwidth(),self.root.winfo_screenheight())) self.root.state('zoomed') tex_frame = Frame(self.root, bd=3, relief=RIDGE) tex_frame.place(x=320, y=400, width=700, height=300) scrolly = Scrollbar(tex_frame, orient=VERTICAL) scrollx = Scrollbar(tex_frame, orient=HORIZONTAL) self.tex_table = ttk.Treeview(tex_frame, columns=("sno","item", "amount"), yscrollcommand=scrolly.set, xscrollcommand=scrollx.set) scrollx.pack(side=BOTTOM, fill=X) scrolly.pack(side=RIGHT, fill=Y) scrollx.config(command=self.tex_table.xview) scrolly.config(command=self.tex_table.yview) self.tex_table.heading("sno", text="Sno") self.tex_table.heading("item", text="Item") self.tex_table.heading("amount", text="Amount") self.tex_table["show"] = "headings" self.tex_table.pack(fill=BOTH, expand=1) self.show() def show(self): data=[{"sno": 1, "item": "apple", "amount": 350}, {"sno": 2, "item": "apple", "amount": 350}, {"sno": 3, "item": "apple", "amount": 350}] self.tex_table.delete(*self.tex_table.get_children()) for row in data: # 按列顺序提取字典对应值传入 self.tex_table.insert('', END, values=(row["sno"], row["item"], row["amount"])) root = Tk() obj = sales(root) root.mainloop()
注:原代码中未使用的全局变量
sno已删除。
灵活优化方案(可选)
如果后续需要调整列的数量或顺序,可以直接通过Treeview的columns属性动态提取对应值,避免硬编码列名:
def show(self): data=[{"sno": 1, "item": "apple", "amount": 350}, {"sno": 2, "item": "apple", "amount": 350}, {"sno": 3, "item": "apple", "amount": 350}] self.tex_table.delete(*self.tex_table.get_children()) # 动态按列顺序提取字典值,适配后续列调整 col_list = self.tex_table["columns"] for row in data: row_values = [row[col] for col in col_list] self.tex_table.insert('', END, values=row_values)
内容的提问来源于stack exchange,提问作者Sakthi Subramani
相关产品推荐
相关产品推荐

