python如何对树视图列中的所有数字求和 [英] python How to sum all the numbers in a treeview column

查看:34
本文介绍了python如何对树视图列中的所有数字求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对总和"的所有数字求和;树视图列:

I need to sum all the numbers of the "Total Sum" Column of Treeview:

代码是:

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

推荐答案

这里有一个方法可以做你想做的,

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)

然后 add() 可以是这样的:

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.

提示:

您可以将输入框的总和自动插入到第三个输入框.

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)

并在代码末尾添加

root.after(1,added)

这将在代码开始时调用该函数.

This will call the function when the code begins.

以上从这里获取的额外答案

如果你不想要按钮,那么删除按钮和它的功能,只需改变你的 update() 如下.

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.

干杯

这篇关于python如何对树视图列中的所有数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆