问题描述
我有一张在Tkinter中使用Treeview制作的表格。我想将第6列中的所有值加在一起,并在输入框中显示该数字。我怎样才能做到这一点?我不热衷于从treeview表中获取值,然后以有意义的方式使用它们。 .get()不存在,.get_children根本不起作用。感谢您的帮助!
from tkinter import *
from tkinter import ttk
f1= tk()
root.geometry("750x500")
Invoice_Maker = LabelFrame(f1,text = "Invoice")
Invoice_Maker.grid(row=8,column=0,columnspan=4)
Qty_Label = Label(Invoice_Maker,text = " Qty:")
Qty_Label.grid(row=0,column=0)
Quantity_Box = Entry(Invoice_Maker,width=15)
Quantity_Box.grid(row=0,column=1)
clicked = StringVar()
clicked.set("Select Item")
Dropdown = OptionMenu(Invoice_Maker,clicked,"Bandana","Du-Rag/Stocking cap","Winter Hats","gloves","A-shirt","Belt","Capdana","Mask","Sleeve","T-shirt RoundNeck","T-shirt V-Neck","T-shirt LongSleeve","Japanese Hat","Sunglass","Small Straw Hat","Cap","Bucket Hat","Safari Hat","Large Straw Hat","Banded Straw Hat","Neon T-Shirt","Panama Jack","Lady Hats","Fedora","Straw Hat Ranchero","Team Hats","Speedy Hat","Misc","Bike Tires","Machetes","Balones")
Dropdown.grid(row=0,column=2)
Style_Label = Label(Invoice_Maker,text = "Style:")
Style_Label.grid(row = 0,column = 3)
StyleMenu = StringVar()
StyleMenu.set("N/A")
Style = OptionMenu(Invoice_Maker,StyleMenu,"Plain","Camo","Neon")
Style.grid(row=0,column=4)
Cost_Label = Label(Invoice_Maker,text = "Cost:")
Cost_Label.grid(row=0,column=5)
Cost = Entry(Invoice_Maker,width=7)
Cost.grid(row=0,column=6)
Retail_Label = Label(Invoice_Maker,text = "Retail:")
Retail_Label.grid(row=0,column=7)
Retail = Entry(Invoice_Maker,width=7)
Retail.grid(row=0,column=8)
Inv_Frame = LabelFrame(Invoice_Maker,bg="red")
Inv_Frame.grid(row=1,columnspan=10)
global Trv
Trv = ttk.Treeview(Inv_Frame)
Trv.pack(side=RIGHT)
Trv["columns"] = ("2","3","4","5","6")
Trv.column("#0",width = 40)
Trv.column(1,width = 80)
Trv.column(2,width = 80)
Trv.column(3,width = 80)
Trv.column(4,width = 80)
Trv.column(5,width = 80)
Trv.column(6,width = 80)
Trv.heading("#0",text="#",anchor=W)
Trv.heading(1,text="Quantity",anchor=W)
Trv.heading(2,text="Item",anchor=W)
Trv.heading(3,text="Style",anchor=W)
Trv.heading(4,text="Cost",anchor=W)
Trv.heading(5,text="Retail",anchor=W)
Trv.heading(6,text="Total",anchor=W)
Scroll = Scrollbar(Inv_Frame,orient="vertical",command=Trv.yview)
Scroll.pack(side=LEFT,fill="y")
def Add_Item():
Trv.insert("",END,text=Quantity_Box.get(),values=(clicked.get(),StyleMenu.get(),Cost.get(),Retail.get(),str(float(Quantity_Box.get())*float(Cost.get()))))
Total_Label = Label(Invoice_Maker,text="Total: ")
Total_Label.grid(row=3,column=8)
Total_Box = Entry(Invoice_Maker,width=10)#This is where I want the total of the numbers in row 6 to go
Total_Box.grid(row=3,column=9)
解决方法
您可以使用Treeview.set()
来获取特定单元格的内容。
因此,您可以按以下方式计算总数:
def calc_total():
total = sum(float(Trv.set(item,6)) for item in Trv.get_children())
Total_Box.delete(0,'end')
Total_Box.insert('end',total)
如果要更新calc_total()
,请致电Total_Box
。