Memory leak when destroying Tk frame containing a figure


I'm writing an application that will show different plots on it's GUI. In
order to switch between the different plot types I'd like to destroy the
first plot and to create a new afterwards. I stumbled into a memory leak
since I don't know how to close matplotlib figures the clean way.

I wrote a small test programm. Pressing the button 'create' creates a figure
and 'delete' should destroy it.
Since the graph class is derived from the Tix.Frame class I would expect
that destroying the Frame would also remove all matplot stuff. But when I do
not implement my own destroy() method in the graph class, destroying the
Frame shows absolutely no effect. The plot simply stays on the screen.
When I overload the Tix.Frame.destroy() method with my own implementation,
as shown below, the plot disappears but not all memory is being released.
When creating and deleting figures, the amount of memory python needs is
constantly growing and python eventually crashes.

I tried to find a solution on the internet but I found nothing really
helpful so far. All examples I found just display something and then just

I appreciate any help!



import matplotlib

from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
from matplotlib.figure import Figure

import Tix
import sys

def destroy(e): sys.exit()

root = Tix.Tk()

class graph(Tix.Frame):
    def __init__(self, master, **kw):
        Tix.Frame.__init__(self, master, **kw)

        self.f = Figure(figsize=(5,4), dpi=100)
        self.a = self.f.add_subplot(111)
        t = arange(0.0,3.0,0.01)
        s = sin(2*pi*t)

        self.canvas = FigureCanvasTkAgg(self.f, master=self.master)
        self.canvas.get_tk_widget().pack(side=Tix.TOP, fill=Tix.BOTH,

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, root )
        self.canvas._tkcanvas.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
    def destroy(self):
class ui(Tix.Frame):
    g = None
    def __init__(self, master, **kw):
        Tix.Frame.__init__(self, master, **kw)
        self.b = Tix.Button(self, text='create', command=self.create)
        self.b2 = Tix.Button(self, text='delete', command=self.delete)

    def delete(self):
    def create(self):
        self.g = graph(root)

View this message in context:
Sent from the matplotlib - users mailing list archive at