Python Average Value In a Tkinter Treeview Column

How to get the Average Value in a Tkinter Treeview Column Using Python

Python Average Value In a Tkinter Treeview Column


import tkinter as tk
from tkinter import *
from tkinter import ttk


root = Tk()
root.title("MAX-MIN-SUM-AVG")

frame_container = tk.Frame(root, padx=10, pady=10, bg='#badc58')
frame_fields = tk.Frame(frame_container, bg='#badc58')

# create treeview
trv = ttk.Treeview(frame_container, columns=(1,2,3,4), show='headings')

trv.column(1, anchor='center', width=100)
trv.column(2, anchor='center', width=100)
trv.column(3, anchor='center', width=100)
trv.column(4, anchor='center', width=100)

trv.heading(1, text='ID')
trv.heading(2, text='Name')
trv.heading(3, text='Quantity')
trv.heading(4, text='Price')

# add items to the treeview
trv.insert("",'end', iid=1, values=(1,"Product 1",100, 10))
trv.insert("",'end', iid=2, values=(2,"Product 2",200, 20))
trv.insert("",'end', iid=3, values=(3,"Product 3",300, 30))
trv.insert("",'end', iid=4, values=(4,"Product 4",400, 400))
trv.insert("",'end', iid=5, values=(5,"Product 5",500, 50))
trv.insert("",'end', iid=6, values=(6,"Product 6",600, 60))

# average value
avg_lbl = tk.Label(frame_fields, text='Average:', font=('Verdana',14), bg='#badc58')
avg_entry = tk.Entry(frame_fields, font=('Verdana',14))

avg_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='e')
avg_entry.grid(row=0, column=1)

# function to display the average value
def getAvg(item=""):
val = 0
for row in trv.get_children(item):
#print(trv.item(row)["values"][3])# print price
val = val + trv.item(row)["values"][3]

val = val/len(trv.get_children())
avg_entry.insert(0,val)


getAvg()

trv.pack()
frame_container.pack()
frame_fields.pack()

root.mainloop()


OUTPUT:

Python Calculate Average Value In a Tkinter Treeview Column






Share this

Related Posts

Previous
Next Post »