[英](Turtle/Python3) How to make a while loop that's independently working forever in turtle?
因此,我要显示的是:Alex与Alice的距离是:(我已经计算出的距离)
我需要将其显示在屏幕顶部。永远刷新,就像在上面显示游戏中的PING统计一样。
我认为这将是一个while循环? 我需要程序的其余部分在不断显示和刷新的同时运行。
这是我解决这个问题的极简方法(嗯,不是全部,我确实带来了一些好处):
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()
拖动Alex或Alice时,它们在屏幕顶部的中心到中心距离会更新。 这使用了一个单独的,不可见的,固定的乌龟来处理显示,该显示执行.undo()
来擦除先前的值,而执行.write()
来显示新的值。 更新距离显示后 ,使海龟彼此转向,确保它们不会被隐藏在不可见的海龟下面(即,不可拉扯),因此甚至可以将其放置在文本上方:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.