首页 > 解决方案 > 如何将树视图值转换为字典

问题描述

如何将树视图值转换为字典

如果按字典方法中的保存按钮树视图值

获取列名并获取列值[{'column_name':'column_value'}]

例子 :[{'item':'apple','amount':'5000'},{'item':'orange','amount'='1000'}]

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')

        self.item=StringVar()
        self.amount=StringVar()

        lbl_name = Label(self.root, text="Enter Item \t:", font=("times new roman", 15, "bold"), bg="white").place(x=40, y=100)
        txt_name = Entry(self.root, textvariable=self.item, font=("times new roman", 15, "bold"), bg="white").place(x=320, y=100, width=350, height=35)

        lbl_name = Label(self.root, text="Amount \t:", font=("times new roman", 15, "bold"), bg="white").place(x=40, y=180)
        txt_name = Entry(self.root, textvariable=self.amount, font=("times new roman", 15, "bold"), bg="white").place(x=320, y=180, width=350, height=35)

        self.btn_add = Button(self.root, text="Add", command=self.add, font=("goudy old style", 15), bg="#4caf50",fg="white", cursor="hand2")
        self.btn_add.place(x=320, y=300, width=150, height=30)
        
        self.btn_select = Button(self.root, text="Save", command=self.save, font=("goudy old style", 15), bg="#4caf50",fg="white", cursor="hand2")
        self.btn_select.place(x=500, y=300, width=150, height=30)

# ==================== treeview ====================================

        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=("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("item", text="Item")
        self.tex_table.heading("amount", text="Amount")

        self.tex_table["show"] = "headings"
        self.tex_table.pack(fill=BOTH, expand=1)

    def add(self):

        self.tex_table.insert('',index="end",values=(self.item.get(),self.amount.get()))
        
    def save(self):
        pass
    
root=Tk()
obj=sales(root)
root.mainloop()

标签: python-3.xtkintertreeview

解决方案


使用treeview.get_children()并遍历它返回的子 id,然后使用self.tex_table.item(x)["values"]来获取该行的值。

这是一个例子

def save(self):
       
    values = []

    for x in self.tex_table.get_children():
        value_dict = {}
        
        for col, item in zip(self.tex_table["columns"], self.tex_table.item(x)["values"]):
            value_dict[col] = item
        
        values.append(value_dict)
    
    print(values)


推荐阅读