简体   繁体   中英

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:

视觉形象

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM