Solved. was: Memory leak problem (while using tkinter)

André andre.roberge at gmail.com
Wed Dec 31 17:37:26 CET 2008


On Dec 31, 12:21 am, André <andre.robe... at gmail.com> wrote:
> I have written a small program (my first Tkinter-based app) to play
> around the idea mentioned on
> http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mo...
> and, in doing so, have encountered a memory leak problem.   I have
> seen mentions on the web of using the delete() method of canvas to
> prevent such problems - which I have tried to do with limited
> success.  Below is the code I wrote; to run it, you will need a small
> image file
> (I used the one found onhttp://alteredqualia.com/visualization/evolve/)
> that is saved under "mona_lisa.png".
>


It appears that the problem occurred due to creating drawing
"contexts" with aggdraw which became orphaned in some ways.  Below is
some changes that appear to solve the problem.  Perhaps this will be
useful to others at some point...

André


[SNIP]
>
> class AggDrawCanvas(Canvas):
>     def __init__(self, width, height, win):
>         Canvas.__init__(self, win)
>         self.image_id = None
>         self.win = win
>         self._width = width
>         self._height = height
>         self._size = width, height
>         self.config(width=width, height=height+20)
>         self.info = self.create_text(width/2, height+20)
>         self.pack()
>         self.dna = DNA(self._width, self._height)
>         self.mutations = 0

         self.img = None

>
>     def draw_dna(self):
>         img = Image.new("RGBA", self._size, "black")
>         self.context = aggdraw.Draw(img)

replace by:

        if self.img is None:
            self.img = Image.new("RGBA", self._size, "black")
            self.context = aggdraw.Draw(self.img)
        else:
            brush = aggdraw.Brush((0, 0, 0), opacity=255)
            self.context.rectangle((0, 0, self._width, self._height),
brush)




>         for gene in self.dna.dna:
>             brush = aggdraw.Brush(tuple(gene[1][0:3]), opacity=gene[1]
> [3])
>             self.context.polygon(gene[0], brush)
>         self.delete(img)
>         self.redraw()
>
[SNIP]



More information about the Python-list mailing list