How to fully delete a turtle

Question:

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?

Asked By: Isaac Saffold

||

Answers:

Did you try deleting the memory-consuming object and then collecting the garbage explicitly using Python’s built-in garbage collector interface?

import gc
...
# Delete memory-consuming object
del window._turtles
# Collect the garbage
gc.collect()
Answered By: Josselin

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.

Answered By: Isaac Saffold

The usual thing to do to get rid of data in turtles is reset():

carl=Turtle()
.... code
carl.reset()

For list of turtles, here kim,donald, fanny and frank are all turtles:

group=[kim,donald,fanny,frank]
for turtle in group:
    turtle.reset()

There is also an convenient code for all turtles on a specific screen, this is a built in list called (screen.turtles). So if You have a screen called screen:

screen=Screen()
...
code
....

for turtle in screen.turtles():
    turtle.reset()
Answered By: Lars Tuff

I face the same problem I have a list of turtle and I want to delete them each time I loop into the list with:

 turtle.undo()
Answered By: Pourya