Declaration of FigureCanvasTkAgg causes memory leak Declaration of FigureCanvasTkAgg causes memory leak tkinter tkinter

Declaration of FigureCanvasTkAgg causes memory leak


I was having this problem with memory leak, and I think I found a solution. In my __init__ method I was creating a frame, and then passing it to a plotting function to do the actual work. In that function, I would create a new matplotlib.figure.Figure instance, which for some reason was not destroyed when the function went out of scope.

To solve it, i did this: in the __init__ method, I created not only the frame but also the figure (complete with axes) and canvas:

    results = tk.Frame(self)    f = Figure()    ax0 = f.add_subplot(211)    ax1 = f.add_subplot(212)    self.canvas = FigureCanvasTkAgg(f, results)    self.canvas.get_tk_widget().pack(expand=True, fill='both')

Then, inside the plotting method,

    ax0, ax1 = self.canvas.figure.get_axes()    ax0.clear()    ax0.plot(x, y)    ax1.clear()    ax1.plot(x, z)    self.canvas.draw()

And just like that, the leak disappeared!


I'm gonna guess this is caused by the pyplot figure not being destroyed when the Tkinter window is closed.
Like in the embedding in tk example try using Figure:

from matplotlib.figure import Figureself.__fig = Figure(figsize=(16,11))

example use:

import Tkinter as tkimport matplotlibmatplotlib.use('TkAgg')from matplotlib.figure import Figurefrom matplotlib.backends.backend_tkagg import FigureCanvasTkAggclass App():    def __init__(self, parent):        self.__drawplotFrame = tk.Frame(parent, width=500, height=500)        self.__drawplotFrame.pack()        self.__fig = Figure(figsize=(16,11))        self.__p = self.__fig.add_subplot(1,1,1)        self.__p.plot(range(10), range(10))        self.__drawplotCanvas = FigureCanvasTkAgg(self.__fig, master=self.__drawplotFrame)        self.__drawplotCanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)root = tk.Tk()App(root)root.mainloop()