【问题标题】:(Turtle/Python3) How to make a while loop that's independently working forever in turtle?(乌龟/Python3)如何在乌龟中制作一个永远独立工作的while循环?
【发布时间】:2018-03-29 19:37:57
【问题描述】:

所以我想做的是显示: Alex 到 Alice 的距离是:(距离我已经计算过了)

我需要将它显示在屏幕顶部.. 永远,令人耳目一新,有点像游戏中的 PING 统计数据显示在顶部..

我认为这将是一个 while 循环?我需要程序的其余部分在不断显示和刷新的同时运行..

【问题讨论】:

标签: python python-3.x while-loop turtle-graphics infinite


【解决方案1】:

这是我对这个问题的极简主义方法(嗯,不完全是,我确实提出了一些细节):

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() 来显示一个新值。让海龟在距离显示更新后转向彼此,以确保它们不会被困在不可见的显示海龟下方(即无法拖动),因此它们甚至可以定位在文本上方:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    相关资源
    最近更新 更多