I've got a simple program that creates a GUI using tkinter
. The GUI contains a button that creates a new tkinter Toplevel
window each time it is pressed. Each toplevel window contains a matplotlib plot created from a custom Figure
class.
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from Tkinter import *
class MainGUI(Tk):
def __init__(self):
Tk.__init__(self)
Button(self, text="new_child", command=self.new_child).pack()
self.mainloop()
def new_child(self):
self.tl = TL()
class TL(Toplevel):
def __init__(self, **kw):
Toplevel.__init__(self, **kw)
self.data = "00000000000"*10000000 # just some data to analyze memory allocation
self._figure = MyFigure(self.data)
self._canvas = FigureCanvasTkAgg(self._figure, master=self)
self._canvas.get_tk_widget().grid(row=0, column=0, sticky="NSWE")
class MyFigure(Figure):
def __init__(self, data):
super(MyFigure, self).__init__()
self._data = data
if __name__ == '__main__':
MainGUI()
The program works as expected, the only problem is that closing a window doesn't free up any memory.
When removing the Figure
from the toplevel window, used memory gets freed correctly, so I assume that the Figure
causes the memory leak.
I read that reference counting doesn't work for Figure
objects that are created using matplotlibs pyplot interface, but this should not apply to my example. (See here for details)
I don't understand what's going on here, so any help would greatly be appreciated.
Thanks in advance.
Edit
I forgot to mention that I already tried to manually invoke the garbage collector with gc.collect()
, but that didn't help.