How to fully delete a turtle

Isaac Saffold picture Isaac Saffold · May 15, 2017 · Viewed 10.5k times · Source

I made a small tkinter game that uses turtle for graphics. It's a simulation of the Triangle Peg Game from Cracker Barrel that is able to tell the player the next best move to make at any point in the game, among other features. Pegs are just instances of a subclass of turtle.RawPen, and I keep plenty of plain instances of RawPen around to draw arrows representing moves.

I noticed that when I restart the game (which calls turtle.bye()) to kill the turtle window, that memory consumption actually increases, as turtles don't seem to be deleted. Even if I call window.clear() beforehand, which clears _turtles in window.__dict__, there are still references to the turtles. I ensured that all the references that I make to them are deleted during restart, so that's not the issue. Is there any way to truly delete a turtle so it can be garbage collected?

Answer

Isaac Saffold picture Isaac Saffold · May 17, 2017

Deleting all my references to objects in the canvas (including, of course, the TurtleWindow) and then destroying the canvas with canvas.destroy() did the trick. Perhaps there are other solutions, but this was the best that I could think of. I appreciate everyone's help, as it will serve me well in the future, at least with objects not created using the turtle API.