【问题标题】:How to make turtle drawn shape move around using arrow keys如何使用箭头键使海龟绘制的形状四处移动
【发布时间】:2020-07-18 22:53:25
【问题描述】:

我必须导入一只乌龟并让它画一个正方形。我已经完成了这一步,但下一步是使用箭头键使该正方形在屏幕上移动。我已经添加了应该允许这种情况发生的代码,但海龟仍然没有移动。它只是出现在屏幕上,我正在按箭头键但没有任何动作。我不确定我的代码中的错误是什么。

import turtle
t = turtle.Turtle

screen = turtle.Screen()
screen.setup(300,300)
screen.tracer(0)

def square():
  for i in range(4):
    turtle.forward(100)
    turtle.left(90)

def move_up():
  turtle.setheading(90) #pass an argument to set the heading of our turtle arrow
  turtle.forward(15)

def move_right():
  turtle.setheading(0) #the direction is east
  turtle.forward(15)

def move_down():
  turtle.setheading(270) #the direction is south
  turtle.forward(15)

def move_left():
  turtle.setheading(180) #the direction is west
  turtle.forward(15)

while True :
    turtle.clear()
    square()            #call function
    screen.update()         # only now show the screen, as one of the frames




screen.onkey(move_up, "Up") 
screen.onkey(move_right, "Right")
screen.onkey(move_down, "Down")
screen.onkey(move_left, "Left")
screen.listen()

【问题讨论】:

    标签: python python-turtle


    【解决方案1】:

    您的主要问题是您试图一次编写整个程序:您没有费心去测试各个部分,而现在您必须修复几个错误才能获得 任何有用的输出。备份,一次编程一个部分,并在继续之前测试每个部分。

    您的直接问题是您没有在需要时将键绑定到操作:

    while True :
        turtle.clear()
        square()            #call function
        screen.update()         # only now show the screen, as one of the frames
    
    screen.onkey(move_up, "Up") 
    screen.onkey(move_right, "Right")
    screen.onkey(move_down, "Down")
    screen.onkey(move_left, "Left")
    screen.listen()
    

    您的绑定前面有一个无限循环:您永远无法访问此代码,因此没有注意箭头键,并且您的屏幕不是listening。您必须在循环之前完成这些事情

    您似乎也对哪些方法适用于一个对象以及哪些方法被称为类调用感到困惑。你还没有实例化一个 Turtle 对象来接受移动命令。

    我建议你回到你的课堂材料,慢慢地学习每一种技术。在你学习的时候将它们添加到你的程序中......并在继续之前测试

    【讨论】:

    • 感谢您的回复。我能够解决我的问题。再次感谢您。
    最近更新 更多