0

I am creating a pi graph where the data will be passed dynamically so created a method to pass variables so that it displays image on canvas but, I am not able to update data of canvas data , so should every time need to destroy the frame and create the total process again so


from tkinter import *
import numpy as np
import pandas as pd
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root = Tk()
root.geometry("500x500")
root.title("Pi Graph")
cash = IntVar()
credit = IntVar()

pi_frame_main = Frame(root)
pi_frame_main.pack(side="bottom", expand=True, fill="both")

def plot(cash_amount, credit_amount):

    pi_frame = Frame(pi_frame_main, height=300, borderwidth=4)

    def func(pct, values):
        """calculating the percentage of the values"""
        absolute = int(pct / 100.0 * np.sum(values))
        return "{:.1f}%\n({:d})".format(pct, absolute)

    if cash_amount != 0 or credit_amount != 0:
        # create frame for plotting

        pi_frame.pack(side='right', padx=10, pady=10, fill='y')

        my_dict = {'NAME': ['Cash', 'Credit'], 'Nos': [cash_amount, credit_amount]}
        print(my_dict)
        df = pd.DataFrame(data=my_dict)
        lbl = ['Cash', 'Credit']
        explode = [0.0, 0.1]
        fig1 = df.plot.pie(title="Cash & Credit", y='Nos', autopct=lambda pct: func(pct, my_dict['Nos']),
                           explode=explode, figsize=(3,3), labels=lbl, shadow=True,
                           legend=False).get_figure()

        fig1.legend(lbl, bbox_to_anchor=(0.75, 1), loc="upper left")
        plot1 = FigureCanvasTkAgg(fig1, pi_frame)
        plot1.get_tk_widget().pack(side='right', fill='y')

Entry(root, textvariable=cash).pack(side="left", padx=5)
Entry(root, textvariable=credit).pack(side="left", padx=5)

Button(root, text="Plot", command=lambda: plot(cash.get(), credit.get())).pack(side="right", padx=5)

root.mainloop()

needed some guidance how to update the the pi graph without destroying the frame

ClownBunny
  • 181
  • 9

0 Answers0