简体   繁体   English

Python 乌龟图形 - 把一只乌龟带到前面

[英]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: animation 发生在它们碰撞在一起的地方,但我希望一只乌龟像这样在另一只乌龟之上:

视觉形象

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?所以,我的问题是 - 我怎样才能做到这一点 - 是否有一行简单的代码,例如: turtle.front() ,如果没有,它是什么?

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:我在对Make one turtle object always above another的回应中简要讨论了这一点,这种简单情况的经验法则是:

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:由于 Python turtle 没有优化零运动,一个简单的方法是将你想要的 turtle 移动一个零量:

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.虽然@Bally 的解决方案有效,但我的问题是每次调整分层时它都会创建一个新的海龟。 And these turtles don't go away.而这些海龟不会 go 离开。 Watch turtle.turtles() grow.观看turtle.turtles()成长。 Even my solution leaves footprints in the turtle undo buffer but I have to believe it consumes less resources.即使是我的解决方案也会在 turtle 撤消缓冲区中留下足迹,但我不得不相信它消耗的资源更少。

Just add this to turtle.py file只需将其添加到 turtle.py 文件中

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)参数 tobring - 这是你当前的乌龟(你想放在前面的那个)

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你可以在你的程序中使用这个 def 或者将它放入 turtle.py 文件中,如果是这样,不要忘记将它添加到命令列表中, - _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希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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