我的GUI中有树视图(n =行,三列)。当用户在标签中输入值并按下按钮时,行将继续添加。假设用户输入了3个值,即3行插入到我的树形视图中。现在,我想将其中一列中的值加起来并在另一个标签中显示。我该怎么做?
def __init__(self, parent, controller):
self.entry=ttk.Entry(self,width=10,)
self.entry.grid(row=2, column=2, ) #value entered by the user and displayed in Temp column
self.entry1=ttk.Entry(self,width=10,)
self.entry1.grid(row=2, column=3, )#value entered by the user and displayed in time column
ttk.Button(self, text='Enter', command=self.insert_data).grid(row=2,column=4, )#calling the method insert data to insert the values entered by the user
self.tree = ttk.Treeview( self, columns=('Temp','time'))
self.tree.heading('#0', text='Number')
self.tree.heading('#1', text='Temp')
self.tree.heading('#2', text='time')
self.tree.column('#1', stretch=tk.YES)
self.tree.column('#2', stretch=tk.YES)
self.tree.column('#0', stretch=tk.YES)
self.tree.grid(row=5, columnspan=4, sticky='nsew')
self.treeview = self.tree
# Initialize the counter
self.i = 1
ttk.Label(self, text='Sum').grid(row=6, column=1, sticky='e')
ttk.Label(self,width = 10,).grid(row=6, column=2, sticky="e") #***I want to display the sume of values entered in the column 'Temp' in this label
def insert_data(self):
self.treeview.insert('', 'end', text=str(self.i), values=(self.entry.get(), self.entry1.get()+"h"))
# Increment counter
self.i = self.i + 1
答案 0 :(得分:0)
如果我理解您要计算插入treeview
列中的总值。为此,您需要先使用treeview
获取tree.get_children()
中的内容,然后对其进行迭代,然后使用index
获取要汇总值的列。在我的代码中是index[0]
。我函数中的sum1 +=
意味着将列中的所有值相加。
您可以将索引更改为[1],以查看总值。
import tkinter as tk
import tkinter.ttk as ttk
def my_values_cal():
sum1 = 0.0
for child in tree.get_children():
sum1 += float(tree.item(child, "values")[0])
lab.config(text=sum1)
print(sum1)
root = tk.Tk()
tree =ttk.Treeview(root, column=("col1", "col2", "col3"), show="headings")
tree.heading('#1', text='Number')
tree.heading('#2', text='Temp')
tree.heading('#3', text='time')
tree.insert("", tk.END, values=(24, "09", "2:00 AM"))
tree.insert("", tk.END, values=(34, "04", "5:00 AM"))
tree.insert("", tk.END, values=(40, "09", "1:00 PM"))
tree.insert("", tk.END, values=(94, "01", "23:00 PM"))
tree.insert("", tk.END, values=("38", "21", "21:00 AM"))
tree.pack()
lab = tk.Label(root, text="Total")
lab.pack()
b = tk.Button(root, text="CALCULATE", command=my_values_cal)
b.pack()
root.mainloop()