python左右箭头键事件无效

时间:2016-02-28 17:10:22

标签: python python-2.7

我是Python的新手,并试图创建一个乌龟形状,一旦用户点击键盘上的左或右箭头键,形状就会向那个方向移动,但是没有任何事情发生。

我正在尝试使用左右箭头键移动播放器,但它不起作用,请提供帮助和建议。

 #Create the player turtle
    player = turtle.Turtle()
    player.color("blue")
    player.shape("triangle")
    player.penup()
    player.speed(0)
    player.setposition(0, -235)
    player.setheading(90)

    playerspeed = 15


    #Move the player Left and Right
    def move_left():
        x = player.xcor()
        x -= playerspeed
        if x < -200:
            x = - 200
        player.setx(x)

    def move_right():
        x = player.xcor()
        x +- playerspeed
        if x < -200:
            x = - 280
        player.setx(x)

#Create Keyboard Bindings
    turtle.listen()
    turtle.onkey(move_left,"Left")
    turtle.onkey(move_right, "Right")

1 个答案:

答案 0 :(得分:0)

您需要在脚本末尾调用turtle.mainloop(),请参阅https://docs.python.org/2/library/turtle.html#turtle.mainloop

这是有效的(它显示了一个蓝色三角形乌龟,根据按下的光标键向左或向右移动;它包括@zondo建议的修复):

import turtle

#Create the player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0, -235)
player.setheading(90)

playerspeed = 15


#Move the player Left and Right
def move_left():
    x = player.xcor()
    x -= playerspeed
    if x < -200:
        x = - 200
    player.setx(x)

def move_right():
    x = player.xcor()
    x += playerspeed
    if x < -200:
        x = - 280
    player.setx(x)

#Create Keyboard Bindings
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")

#Start the main loop
turtle.mainloop()