【问题标题】:Turtle's Position Doesn't Change After Moving with Arrow Keys使用箭头键移动后海龟的位置不会改变
【发布时间】:2020-03-21 04:02:37
【问题描述】:

我正在尝试查找由用户使用 wasd 键控制的海龟的位置。我注意到海龟的位置在while (True) 块内的打印语句中似乎从未改变。你们有什么建议(下面的相关代码供参考)?

注意:我知道while(True) 是错误的形式;这只是一个尖峰。

import turtle

def Setupcontrols(turtle, window):
  window.onkey(lambda: turtle.sety(turtle.ycor()+15), 'w')
  window.onkey(lambda: turtle.setx(turtle.xcor()-15), 'a')
  window.onkey(lambda: turtle.setx(turtle.xcor()+15), 'd')
  window.onkey(lambda: turtle.sety(turtle.ycor()-15), 's')
  window.listen()

def Setupuser(myTurtle,window):
  window.bgcolor("white")
  window.setup (width=400, height=400, startx=0, starty=0)
  myTurtle.speed(2)
  myTurtle.shape('turtle')
  myTurtle.color("blue")
  myTurtle.penup()
  myTurtle.delay(0)
  myTurtle.left(90)
  window.exitonclick()

def main():
  wn=turtle.Screen()
  Gameturtle=turtle.Turtle()
  Setupuser(Gameturtle, wn)
  Setupcontrols(Gameturtle, wn)
  while (True):
    print(Gameturtle.position())

main()

【问题讨论】:

  • while True: 在这里不仅是糟糕的形式:对于该循环的(无限)持续时间,其中的print 绝对是您的程序唯一在做的事情 i>.
  • 我提到这是一个尖峰(又名概念证明)。我还有其他工作代码,但这个功能让我有些头疼。关于职位不变的任何建议?

标签: python-2.7 turtle-graphics keyboard-events


【解决方案1】:

我相信您只能将函数用于您的 onkey 命令。示例:

import turtle
t = turtle.Turtle()
screen = turtle.Screen()

def moveForward():
   t.forward(1)

screen.onkey(moveForward,'right')
screen.listen()

希望这会有所帮助!

【讨论】: