Home > Back-end >  Update plot matplotlib tkinter
Update plot matplotlib tkinter

Time:08-26

I have the following piece of code:

import tkinter as tk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg)
from matplotlib.figure import Figure

root = tk.Tk()

figure = Figure()
figure_canvas = FigureCanvasTkAgg(figure,master=root) 

axes = figure.add_subplot(1,1,1)
axes.plot([1,2,3],[1,2,3])

figure_to_pack_d1 = figure_canvas.get_tk_widget()
figure_to_pack_d1.pack(fill=tk.BOTH)

def plot_axes():
    axes.clear()
    axes.plot([1,2,3],[3,2,1])
tk.Button(root,command=plot_axes,text="Update plot").pack()

root.mainloop()

It's supposed to generate a simple GUI with a matplotlib plot and a button (done correctly). When you press the button, the plot should change. When the button gets pressed, seems that nothing is happening, but if you force to update the window (changing it's size) it gets updated correctly. Is there any way to update the plot immediatly after the button is pressed? I've tried some methods like root.update(), axes.update({}), figure.canvas.flush_events()... But none of them worked.

Thank you so much!

CodePudding user response:

I was finnaly able to find my own answer. The actual way to update the plot is with de command:

figure_canvas.draw()

So, the script looks like:

import tkinter as tk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg)
from matplotlib.figure import Figure

root = tk.Tk()

figure = Figure()
figure_canvas = FigureCanvasTkAgg(figure,master=root) 

axes = figure.add_subplot(1,1,1)
axes.plot([1,2,3],[1,2,3])

figure_to_pack_d1 = figure_canvas.get_tk_widget()
figure_to_pack_d1.pack(fill=tk.BOTH)

def plot_axes():
    axes.clear()
    axes.plot([1,2,3],[3,2,1])
    figure_canvas.draw()
tk.Button(root,command=plot_axes,text="Update plot").pack()

root.mainloop()
  • Related