简体   繁体   English

(Turtle / Python3)如何制作一个在Turtle中永远独立工作的while循环?

[英](Turtle/Python3) How to make a while loop that's independently working forever in turtle?

So what I want to do, is display: The distance of Alex from Alice is: (distance I calculated already) 因此,我要显示的是:Alex与Alice的距离是:(我已经计算出的距离)

I need this to be displayed on top of the screen.. forever,refreshing, kind of like PING statistics in games shows on top there.. 我需要将其显示在屏幕顶部。永远刷新,就像在上面显示游戏中的PING统计一样。

I assume it would be a while loop? 我认为这将是一个while循环? I need the rest of the program running while this is constantly displaying and refreshing.. 我需要程序的其余部分在不断显示和刷新的同时运行。

Here's my minimalist approach to this problem (well, not totally, I did throw in a couple of niceties): 这是我解决这个问题的极简方法(嗯,不是全部,我确实带来了一些好处):

from turtle import Turtle, Screen

FONT_SIZE = 24
FONT = ('Arial', FONT_SIZE, 'normal')

def turtle_drag(turtle, other, x, y):
    turtle.ondrag(None)  # disable event hander in event hander
    turtle.goto(x, y)
    display.undo()  # erase previous distance
    distance = turtle.distance(other)
    display.write('Distance: {:.1f}'.format(distance), align='center', font=FONT)
    turtle.setheading(turtle.towards(other))  # make them always look
    other.setheading(other.towards(turtle))  # lovingly at each other
    turtle.ondrag(lambda x, y: turtle_drag(turtle, other, x, y))  # reenable

screen = Screen()
screen.setup(500, 500)

display = Turtle(visible=False)
display.penup()
display.goto(0, screen.window_height() / 2 - FONT_SIZE * 2)
display.write('', align='center', font=FONT)  # garbage for initial .undo()

Alex = Turtle('turtle')
Alex.speed('fastest')
Alex.color('blue')
Alex.penup()

Alice = Turtle('turtle')
Alice.speed('fastest')
Alice.color('red')
Alice.penup()

turtle_drag(Alex, Alice, -50, -50)  # initialize position and event hander
turtle_drag(Alice, Alex, 50, 50)

screen.mainloop()

As you drag Alex or Alice, their center to center distance at the top of the screen updates. 拖动Alex或Alice时,它们在屏幕顶部的中心到中心距离会更新。 This uses a separate, invisible, stationary turtle handling the display who does .undo() to erase a previous value and .write() to display a new one. 这使用了一个单独的,不可见的,固定的乌龟来处理显示,该显示执行.undo()来擦除先前的值,而执行.write()来显示新的值。 Making the turtles turn towards each other after the distance display is updated ensures they don't get trapped underneath the invisible display turtle (ie undragable) so they can even be postitioned atop the text: 更新距离显示 ,使海龟彼此转向,确保它们不会被隐藏在不可见的海龟下面(即,不可拉扯),因此甚至可以将其放置在文本上方:

在此处输入图片说明

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

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