问题
I need to sum all the numbers of the "Total Sum" Column of Treeview:
The code is:
from tkinter import ttk
import tkinter as tk
from tkinter import*
def update():
listBox.insert('','end',value=('APL', t1.get(),t2.get(),t3.get()))
root = tk.Tk()
root.geometry('1000x600')
e8 = tk.Label(root,text="APL").grid(row=1,column=0)
t1 = tk.Entry(root)
t1.grid(row=1,column=1)
t2 = tk.Entry(root)
t2.grid(row=1,column=2)
t3 = tk.Entry(root)
t3.grid(row=1,column=3)
cols = ('name', 'No1', 'No2', 'total sum')
listBox = ttk.Treeview(root, columns=cols, show='headings')
for col in cols:
listBox.heading(col, text=col)
listBox.grid(row=1, column=0, columnspan=2)
listBox.place(x=10, y=300)
b = tk.Button(root,text='Update Listbox',command=update)
b.grid(row=3)
root.mainloop()
回答1:
Here is a method to do what you want,
Start of by making a button and a function to it:
b1 = tk.Button(root,text='Add Listbox',command=add)
b1.grid(row=4)
then the add()
can be something like:
def add():
total = 0.0
for child in listBox.get_children():
total += float(listBox.item(child, 'values')[3])
lbl = Label(root,text=total,font=('helvetica',18))
lbl.grid(row=5)
This will print the total of the item in the final column.
Tip:
You can insert the sum of entry box automatically onto the third entry box.
def added():
# Sets the sum of values of e1 and e2 as val of e3
try :
sum_tk.set((int(t1.get().replace(' ', '')) + int(t2.get().replace(' ', ''))))
except :
pass
root.after(1, added) # reschedule the event
return
Then you should define something like and change the code to below.
sum_tk = tk.StringVar()
t3 = tk.Entry(root,textvariable=sum_tk)
t3.grid(row=1,column=3)
and towards the end of the code, add
root.after(1,added)
This will call the function when the code begins.
Above extra answer taken from here
If you dont want buttons, then remove the button and its function and just change your update()
as below.
def update():
if t1.get() == '' or t2.get() == '' or t3.get() == '':
pass
else:
listBox.insert('','end',value=('APL', t1.get(),t2.get(),t3.get()))
total = 0.0
try:
for child in listBox.get_children():
total += float(listBox.item(child, 'values')[3])
except:
pass
print(total)
lbl = Label(root,text=total,font=('helvetica',21))
lbl.grid(row=5)
t1.delete(0,'end')
t2.delete(0,'end')
t3.delete(0,'end')
Hope this helped, do let me know if any doubts or errors.
Cheers
来源:https://stackoverflow.com/questions/63885475/python-how-to-sum-all-the-numbers-in-a-treeview-column