首先,我们要了解基础知识。
为了让用户能够通过按键与乌龟进行交互,我们需要让窗口listen进行按键操作。由于您的屏幕名为wn,因此只需调用wn.listen()即可。
现在海龟图形正在监听按键,你将如何告诉程序通过按键做某事?功能!假设您希望每次按下某个键时都创建一个新海龟;你需要像这样定义一个函数(你可以使用lambda作为函数,但现在,让我们坚持使用def):
def create_new_turtle():
new_turtle = turtle.Turtle()
请记住,在定义函数时,不应将任何positional arguments 传递到括号中,因为在使用函数时将无法传递参数,从而导致TypeError。
现在,让我们来看看我们如何在运行时在按键被按下时实际调用这些函数。启动wn.listen() 后,您现在只需要wn.onkey 或wn.onkeypress。使用上面的函数,如果你想在用户每次按下 SPACE 键时创建一个新的海龟:
wn.onkey(create_new_turtle, 'space')
你明白为什么我们不能将位置参数传递给函数吗?可以看到,在使用wn.onkey里面的函数时,我们没有调用它(因为我们没有在函数的右边加上括号); wn.onkey 为我们做这件事。
利用我们学到的知识,让我们看看它们的实际应用:
import turtle
#Screen
wn = turtle.Screen()
wn.bgcolor("lightblue")
#Turtle Player
spaceship = turtle.Turtle()
spaceship.color("red")
spaceship.penup()
#Constant
speed = 1
def up():
spaceship.setheading(90)
def down():
spaceship.setheading(270)
def left():
spaceship.setheading(180)
def right():
spaceship.setheading(0)
wn.listen()
wn.onkey(up, 'Up')
wn.onkey(down, 'Down')
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')
while True:
spaceship.forward(speed)
你能猜出这是做什么的吗?这很明显;当用户点击'Up'箭头时,将调用上面定义的up函数,当用户点击'Down'箭头时,将调用上面定义的down函数,以此类推。
为单个命令定义整个函数似乎不对,我们不能这样做
wn.onkey(spaceship.setheading(90), 'Up')
wn.onkey(spaceship.setheading(270), 'Down')
wn.onkey(spaceship.setheading(180), 'Left')
wn.onkey(spaceship.setheading(0), 'Right')
就像最受好评的答案一样,解决方案是使用lambda,可以将上面导致错误的代码更正为
wn.onkey(lambda: spaceship.setheading(90), 'Up')
wn.onkey(lambda: spaceship.setheading(270), 'Down')
wn.onkey(lambda: spaceship.setheading(180), 'Left')
wn.onkey(lambda: spaceship.setheading(0), 'Right')
最后,如果你想让你的海龟在每次转弯时最大转动90 度,你可以在函数中使用if 语句来避免180 度转弯(随着函数变得越来越高级,最好使用def来定义函数而不是使用lambda):
import turtle
#Screen
wn = turtle.Screen()
wn.bgcolor("lightblue")
#Turtle Player
spaceship = turtle.Turtle()
spaceship.color("red")
spaceship.penup()
#Constant
speed = 1
def up():
if spaceship.heading() != 270:
spaceship.setheading(90)
def down():
if spaceship.heading() != 90:
spaceship.setheading(270)
def left():
if spaceship.heading() != 0:
spaceship.setheading(180)
def right():
if spaceship.heading() != 180:
spaceship.setheading(0)
wn.listen()
wn.onkey(up, 'Up')
wn.onkey(down, 'Down')
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')
while True:
spaceship.forward(speed)
试运行: