【问题标题】:python left and right arrow key event not workingpython左右箭头键事件不起作用
【发布时间】:2016-02-28 17:10:21
【问题描述】:

我是 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")

【问题讨论】:

  • 一方面,在move_right() 中,您说x +- playerspeed 而不是x += playerspeed。我假设这是一个错字,但谁知道呢。
  • 我已经更正了这个,但是玩家仍然没有移动。

标签: python python-2.7


【解决方案1】:

脚本末尾需要调用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()

【讨论】:

  • 我已经调用了主循环,但没有在上面的代码中显示它。你能建议吗
  • 不客气;请将答案标记为已选择,以便其他人知道此问题已回答。
猜你喜欢
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多