So what I want to do, is display: The distance of Alex from Alice is: (distance I calculated already)
I need this to be displayed on top of the screen.. forever,refreshing, kind of like PING statistics in games shows on top there..
I assume it would be a while loop? 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. 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. 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.