How do I embed a matplotlib animation to a tkinter frame?

17 Views Asked by At

I am fairly new to python but know a decent amount.

I am currently trying to develop a stock market sim which extracts stock prices from yahoo finance and plots it on a tkinter frame using matplotlib FuncAnimation.

I have managed to get the web scraping and append to a csv working thanks to a tutorial but am struggling to actually plot the prices on a frame which updates every time the stock price is fetched.

I have had a look at other posts about similar issues, but I'm not too sure how I can apply it in the context of my own project.

I have had a look into threading since the web scraping has a while loop to fetch the prices, but that is an issue for another day as I am currently just using another terminal to update the csv file. Here is my code for generating the graph:

generate_graph = ctk.CTkButton(master=self.market_frame, width=150, text='Generate', command=lambda: plot())
    generate_graph.place(relx=0.25, rely=0.9)

    def plot():

        plt.style.use('fivethirtyeight')

        fig = plt.Figure(figsize = (5,4),
                    dpi = 50)
        
        ax = fig.add_subplot(111)

        def update_data(frame_number):

            data = pd.read_csv('data.csv')
            x_data = data['x_value']
            s_price = data['stock_price']

            ax.clear()
            ax.plot(x_data, s_price)

        ani = FuncAnimation(fig, update_data, interval=1000)

        canvas = FigureCanvasTkAgg(fig, master=self.market_frame)
        canvas.get_tk_widget().place(relx=0.085, rely=0.12)
        canvas.draw()

After clicking Generate multiple times

When running my web scrape in another terminal, the graph only updates when I click 'Generate'. Is there anyway I can get the FuncAnimation to update automatically instead of having to always click 'Generate'.

0

There are 0 best solutions below