python - 如何使用箭头键使海龟绘制的形状四处移动
问题描述
我必须导入一只乌龟并让它画一个正方形。我已经完成了这一步,但下一步是使用箭头键使该正方形在屏幕上移动。我已经添加了应该允许这种情况发生的代码,但海龟仍然没有移动。它只是出现在屏幕上,我正在按箭头键但没有任何动作。我不确定我的代码中的错误是什么。
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()
解决方案
您的主要问题是您试图一次编写整个程序:您没有费心去测试各个部分,而现在您必须修复几个错误才能获得任何有用的输出。备份,一次编程一个零件,并在继续之前测试每个零件。
您的直接问题是您没有在需要时将键绑定到操作:
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 对象以获取移动命令。
我建议你回到你的课堂材料,慢慢地学习每一种技术。在您学习时将每个添加到您的程序中......并在继续之前进行测试。
推荐阅读
- reactjs - 错误对象不可迭代(无法读取属性 Symbol(Symbol.iterator))
- mysql - 如何在 Rails 应用程序中克隆表并保持结构同步?
- timer - Eclipse Microprofile 中不同的 Timer 单元指定了什么?
- selenium - 如何将代理应用到scrapy+selenium
- erlang - rebar3_auto 崩溃
- javascript - three.js 如何确保在加载模型后加载其他 javascript 文件
- gitlab - 输入 gitlab-ctl reconfigure 时如何修复语言环境
- python - Panda Dataframe 在编辑某些值时向 .csv 添加更多列
- ios - ARKit 可以实现圆柱目标跟踪吗?
- .net - 为什么 web api 方法被多次调用