Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Turtle Graphics - Bring A Turtle To The Front

I have two turtles in my program. An animation happened where they collide together, but I would like one turtle to be on top of the other like this:

Visual Image

So, my question is - how can I make this happen - is there a simple line of code such as: turtle.front(), if not what is it?

like image 355
A Display Name Avatar asked Sep 03 '25 01:09

A Display Name


1 Answers

I discuss this briefly in my response to Make one turtle object always above another where the rule of thumb for this simple situation is:

last to arrive is on top

Since Python turtle doesn't optimize away zero motion, a simple approach is to move the turtle you want on top by a zero amount:

import turtle

def tofront(t):
    t.forward(0)

gold = turtle.Turtle("square")
gold.turtlesize(5)
gold.color("gold")
gold.setx(-10)

blue = turtle.Turtle("square")
blue.turtlesize(5)
blue.color("blue")
blue.setx(10)

turtle.onscreenclick(lambda x, y: tofront(gold))

turtle.done()

The blue turtle overlaps the gold one. Click anywhere and the situation will be reversed.

Although @Bally's solution works, my issue with it is that it creates a new turtle everytime you adjust the layering. And these turtles don't go away. Watch turtle.turtles() grow. Even my solution leaves footprints in the turtle undo buffer but I have to believe it consumes less resources.

like image 71
cdlane Avatar answered Sep 04 '25 15:09

cdlane