'Turtle.onkeypress confuses me. Why does it not work?

so I've been running my code for a few times no and the onkeypress Method seems to not work like it is intended to.

So whenever i run the python script, all the move methods are executed once and work like they should. But they do not execute whenever i press one of the specified buttons (e.g. "w") What am i doing wrong? And how do i get rid off it? Thanks in advance

def move_up():
    y = snake.ycor()
    y += 20
    snake.sety(y)
    print("l")


def move_down():
    y = snake.ycor()
    y -= 20
   snake.sety(y)
   print("l")


def move_left():
    x = snake.xcor()
    x -= 20
    snake.setx(x)
    print("l")


def move_right():
    x = snake.xcor()
    x += 20
    snake.setx(x)
    print("l")

# snake
snake = turtle.Turtle()
snake.speed(0)
snake.shape("square")
snake.color("white")
snake.penup()
snake.goto(-290, 290)



# keyboard input
wn.listen()
wn.onkeypress(move_up(), "w")
wn.onkeypress(move_down(), "s")
wn.onkeypress(move_left(), "a")
wn.onkeypress(move_right(), "d")

# Main game loop
while True:
    wn.update()


Solution 1:[1]

wn.onkeypress(move_up(), "w")

This line is equivalent to "call move_up() right now, take its return value, and register it to the 'w' keypress event". Similarly, the following three lines call move_down, move_left, and move_right immediately, without waiting for the user to press a button.

You should pass your functions as arguments without calling them. Skip the parens:

wn.onkeypress(move_up, "w")
wn.onkeypress(move_down, "s")
wn.onkeypress(move_left, "a")
wn.onkeypress(move_right, "d")

Solution 2:[2]

Why don't you try this?

 def up():
    head.setheading(90)
    head.forward(10)

def down():
    head.setheading(270)
    head.forward(10)

def left():
    head.setheading(180)
    head.forward(10)

def right():
    head.setheading(0)
    head.forward(10)

wn.listen()
wn.onkeypress(up, "Up")
wn.onkeypress(down, "Down")
wn.onkeypress(left, "Left")
wn.onkeypress(right, "Right")

while True:
    wn.update()

wn.mainloop()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin
Solution 2 Abi