[英](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.