Turtle.onkeypress not working (Python)

I'm very new to Python and have made a couple small games during a Python Learning course but never at home. So recently I began making a game, but after just 10 minutes I stumbled upon a problem:

Nothing happened when I pressed "W" although I had writen onkeypress in the code. See for your self:

(It's designed for full screen)

import turtle

s = turtle.Screen()

g = turtle.Turtle()

t = turtle.Turtle()

#Ground

t.speed(0)

t.up()

t.goto(-1000,-200)

t.down()

t.goto(1000,-200)


#Player

g.speed(0)

PlayerX = -600

def moveX():

    g.clear()

    global PlayerX

    g.up()

    g.goto(PlayerX,-99)

    g.down()

    g.color("Slate Gray")

    g.begin_fill()

    g.circle(-50)

    g.end_fill()

    PlayerX = PlayerX - 1




turtle.onkeypress(moveX, "w")

moveX()

Btw I'm fully aware I haven't made a go backwards button.


I think it's called onkey not onkeypress. Also I think you need to listen (and add a mainloop if you want it to run):

turtle.onkey(moveX, "w")
turtle.listen()
moveX() # draw things first
turtle.mainloop()

You may need to revisit the numbers you are using to make sure the shape is on the window.


Along with @doctorlove's spot on correction (+1) of adding listen() to allow the window to receive keyboard events, a couple of comments:

First, click on the window with your mouse to make it active otherwise it won't respond to the keyboard. Second, it can be helpful to deactivate the event handler while in the event hander, and reactivate it on the way out, to avoid problems if someone repeatedly presses the key very fast.

Here's the second comment along with some other code suggestions:

from turtle import Turtle, Screen

screen = Screen()
screen.setup(1200, 500)

# Ground

ground = Turtle()
ground.speed('fastest')

ground.penup()
ground.goto(-1000, -200)
ground.pendown()
ground.forward(2000)

# Player

player = Turtle()
player.speed('fastest')

PlayerX = -600

def moveX():
    global PlayerX

    screen.onkeypress(None, "w")  # disable handler in handler
    player.clear()
    player.penup()
    player.goto(PlayerX, -99)
    player.pendown()
    player.color("Slate Gray")
    player.begin_fill()
    player.circle(-50)
    player.end_fill()

    PlayerX -= 1

    screen.onkeypress(moveX, "w")  # reenable handler

screen.listen()

moveX()

screen.mainloop()  # change import & use turtle.mainloop() if Python 2

mainloop() isn't required to run but the program will exit after your initial moveX() call without it. mainloop() turns control over to the Tk event handler so some events may not fire without it.

You'll need to change onkeypress() to onkey() if this is Python 2 as well as change the way that mainloop() is invoked.