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:
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?
-
1I think if you will draw turtle 1 after drawing turtle 2, yellow will be rendered above blue automaticallyxor– xor2016年06月28日 20:57:51 +00:00Commented Jun 28, 2016 at 20:57
-
Thanks, I will try it!A Display Name– A Display Name2016年06月28日 21:01:47 +00:00Commented Jun 28, 2016 at 21:01
2 Answers 2
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.
Comments
Just add this to turtle.py file
def tofront(self, tobring):
newfront = tobring.clone()
tobring.ht()
return newfront
works correct, so method - sould return you new clone of turtle, on the top of all other turtles. parameter tobring - it's your current turtle (the one you want to bring to front)
you can use this def in your program or put it into turtle.py file if so, don't forget to add it to list of commands, - _tg_turtle_functions
_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'tofront', 'color',
I did it after clone command
Hope this will help you
1 Comment
turtle.turtles()) I've provided a simpler alternate answer to this question that doesn't involve creating new turtles.Explore related questions
See similar questions with these tags.