2

I am writing a small program, with the intention to update matplotlib graphs periodically throughout. For this I intend to use clear() and redraw the graph. The clear function does work when called from within the method that creates the graph, but it does not work, when called from a button, eventhough the graph is given as a Parameter.

Below is runnable code in it's most basic form to illustrate the problem. In this case, clicking the "Update" button does nothing. How would I fix that button to clear the graph?

import matplotlib.pyplot as plt 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import numpy as np

class MainWindow(tk.Frame):
    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.add_graph()

    def add_graph(self):         
        fig_sig = plt.figure(figsize=(4,2))
        graph = fig_sig.add_subplot(111)
        y_values = [0,1,2,3,4,5]   
        x_values = [1,2,3,4,5,6]
        graph.plot(x_values, y_values)
        canvas = FigureCanvasTkAgg(fig_sig, master=root)
        canvas_widget=canvas.get_tk_widget()   
        canvas_widget.grid(row = 1, column = 0, columnspan = 3)
        canvas.draw()
        self.add_widgets(root, graph)
        #graph.clear()  # Calling graph.clear() here does clear the graph

    def add_widgets(self, parent, graph):
        update_btn = tk.Button(parent, text = "Update", command = lambda: self.update_graph(graph))
        update_btn.grid(row = 8, column = 3)

    def update_graph(self, graph):
        graph.clear()   # calling graph.clear() here does nothing

root = tk.Tk()
oberflaeche = MainWindow(master = root)
oberflaeche.mainloop()   
Tasmotanizer
  • 337
  • 1
  • 5
  • 15

1 Answers1

2

you need to "update" canvas in that case.

define your canvas as: self.canvas = FigureCanvasTkAgg(fig_sig, master=root)

and "update" it:

def update_graph(self, graph):
    graph.clear()   # calling graph.clear() here does nothing
    self.canvas.draw()
ncica
  • 7,015
  • 1
  • 15
  • 37
  • So how does it work `graph.clear()` is called inside `add_graph`, since this happens after the first call to `canvas.draw`? – RFairey Feb 27 '20 at 15:10
  • @RFairey Read Python and Tkinter lambda function - https://stackoverflow.com/questions/11005401/python-and-tkinter-lambda-function/11005426#11005426 – ncica Feb 27 '20 at 15:21
  • I tried that first and that didn't help (although I agree it will become important once there are several plots on screen). Only calling `canvas.draw()` in `update_graph` solved the issue as in the answer, but un-commenting the original `graph.clear()` still works, even though it's after canvas.draw(), and without changing the lambda. – RFairey Feb 27 '20 at 16:14