首页 > 解决方案 > 如何使用箭头键使海龟绘制的形状四处移动

问题描述

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

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()

标签: pythonpython-turtle

解决方案


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

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

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()

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

您似乎也对哪些方法适用于对象以及您将哪些方法称为类调用感到困惑。您尚未实例化 Turtle 对象以获取移动命令。

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


推荐阅读