如何调用在按键上打印Turtle坐标的函数?

时间:2019-04-19 16:43:42

标签: python python-3.x turtle-graphics

我试图在每次移动时在控制台或画布上为乌龟打印新坐标,同时擦除旧坐标。每次按键后如何调用在屏幕上打印坐标的函数?

这是我到目前为止所拥有的:

def writer(x, y):
    turtle1.write((x, y), align='center', font=FONT)
    turtle1.undo()

wn.onkey(writer, "Up")
wn.onkey(writer, "Down")
wn.onkey(writer, "Left")
wn.onkey(writer, "Right")

1 个答案:

答案 0 :(得分:0)

您的代码只是一厢情愿。您缺少进口商品和其他重要信息(例如turtle1FONT的声明)。您假设onkey()将坐标传递到其事件处理程序(不是)。要完成您想做的事情,还需要更多的设置。我建议两只乌龟,一只乌龟通过在屏幕上明显移动来响应键盘事件,另一只乌龟坐在原点上写出第一只乌龟的坐标:

from turtle import Screen, Turtle

FONT_SIZE = 18

FONT = ('Arial', FONT_SIZE, 'normal')

def move_up():
    wn.onkey(None, 'Up')  # disable handler inside handler
    turtle1.sety(turtle1.ycor() + 5)
    writer()
    wn.onkey(move_up, 'Up')

def move_down():
    wn.onkey(None, 'Down')
    turtle1.sety(turtle1.ycor() -5)
    writer()
    wn.onkey(move_down, 'Down')

def move_left():
    wn.onkey(None, 'Left')
    turtle1.setx(turtle1.xcor() - 5)
    writer()
    wn.onkey(move_left, 'Left')

def move_right():
    wn.onkey(None, 'Right')
    turtle1.setx(turtle1.xcor() + 5)
    writer()
    wn.onkey(move_right, 'Right')

def writer():
    turtle2.undo()
    turtle2.write(turtle1.position(), align='center', font=FONT)

turtle1 = Turtle('circle')
turtle1.penup()

turtle2 = Turtle(visible=False)
turtle2.penup()
turtle2.sety(-FONT_SIZE / 2)
turtle2.write(turtle1.position(), align='center', font=FONT)

wn = Screen()

wn.onkey(move_up, 'Up')
wn.onkey(move_down, 'Down')
wn.onkey(move_left, 'Left')
wn.onkey(move_right, 'Right')

wn.listen()
wn.mainloop()