1

I am currently trying to embed a matplotlib figure into a GUI using tkinter. My problem arises from trying to create a button to update the figure showing in the FigureCanvasTkAgg.

This is how I set up the original plot and everything works great

self.canvas = FigureCanvasTkAgg(figure, self.curve_plot)
self.canvas.draw()
self.canvas.get_tk_widget().pack(expand=tk.TRUE, fill=tk.BOTH)

self.toolbar = CustomToolbar(self.canvas, self.curve_plot)
self.toolbar.update()
self.canvas._tkcanvas.pack(fill=tk.BOTH)

I created another method where I want to pass a new figure to the Canvas and update it.

def update_graph(self, new_fig):
    self.canvas.figure = figure
    self.canvas.draw()
    self.canvas.get_tk_widget().pack(expand=tk.TRUE, fill=tk.BOTH)

This draws the new figure but it is not on the correct scale that the previous figure was on (note both figures are essentially identical with different data for testing purposes).

I was previously clearing the canvas using

self.canvas.get_tk_widget().destroy()

Then recalling the original code a the top of this post with the new figure. I'd rather avoid destroying the widget and recreating it as it looks strange on the GUI.

Cr1064
  • 409
  • 5
  • 15
  • is there any particular reason you're creating a whole new figure, instead of changing the content of the existing figure? – Diziet Asahi Aug 16 '19 at 11:40
  • I think there are two options: (1) Keep the figure and exchange its content, (2) Create a new FigureCanvas for a new figure and replace the old canvas with it. Changing the figure of an existing canvas seems problematic. – ImportanceOfBeingErnest Aug 16 '19 at 11:48
  • How can I replace the old canvas with a new FigureCanvas? Would I need to destroy the old one and pack in the new canvas? – Cr1064 Aug 16 '19 at 13:02
  • https://stackoverflow.com/questions/59001195/how-to-update-a-graph-created-by-matplotlib-in-tkinter This link will help to update your canvas. – Megastar Feb 28 '21 at 20:40

0 Answers0