0

So im working on something very basic in pycharm and my onkeypress wont work. What i mean is that when i press w, s, Up or Down, nothing happens.

Here is the code:

# Functions
def paddle_a_up():
 y = paddle_a.ycor()
 y += 20
 paddle_a.sety(y)

def paddle_a_down():
 y = paddle_a.ycor()
 y -= 20
 paddle_a.sety(y)

def paddle_b_up():
 y = paddle_b.ycor()
 y += 20
 paddle_b.sety(y)

def paddle_b_down():
 y = paddle_b.ycor()
 y -= 20
 paddle_b.sety(y)

# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up(), "w")
wn.onkeypress(paddle_a_down(), "s")
wn.onkeypress(paddle_b_up(), "Up")
wn.onkeypress(paddle_b_down(), "Down")

Thank you in advance

telemaster
  • 21
  • 5
  • Check this post: https://stackoverflow.com/questions/45545469/turtle-onkeypress-not-working-python – Mike67 Sep 21 '20 at 03:44

1 Answers1

1

This is a common beginner's error with turtle events. In these calls:

wn.onkeypress(paddle_a_up(), "w")
wn.onkeypress(paddle_a_down(), "s")
wn.onkeypress(paddle_b_up(), "Up")
wn.onkeypress(paddle_b_down(), "Down")

you should be passing the names of your functions to call later, when the event occurs, not calling them yourself. It should be:

wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • wow, worked perfectly. but what do u mean with " _passing the names of your functions to call later, when the event occurs, not calling them yourself_"??? i didn't quite understand that. – telemaster Sep 21 '20 at 04:27
  • @telemaster, a function is another datatype, like `int`, it can be stored and passed around. Event handler setup fuctions like `onkeypress` take a function as an argument to call if/when the particular key, e.g. `"Down"`, is pressed. By including parentheses, you called the `paddle_b_down()` function, you instead needed to pass the `paddle_b_down` function. – cdlane Sep 21 '20 at 04:39