这是我对这个问题的极简主义方法(嗯,不完全是,我确实提出了一些细节):
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() 来显示一个新值。让海龟在距离显示更新后转向彼此,以确保它们不会被困在不可见的显示海龟下方(即无法拖动),因此它们甚至可以定位在文本上方: