Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turtle not detecting key presses in Python [duplicate]

Here is a HUGELY simplified version of my code:

from turtle import Turtle, Screen
import time

speed_x = 20
speed_y = 29

def move_right():
    print('exectuted')
def game_loop():
    ball.goto(ball.xcor() + speed_x, ball.ycor() + speed_y)

    window.update()

    window.ontimer(game_loop, 1)


window = Screen()
time.sleep(2)

ball = Turtle(shape='circle')
ball.color('white')


paddle = Turtle(shape='square')

window.onkeypress(move_right, 'Right')
window.onkeypress(move_right, 'D')

game_loop()

window.mainloop()

I expected the move_right() function to execute (which for testing should have printed out something)

But I get nothing

like image 945
Aadvik Avatar asked Oct 21 '25 13:10

Aadvik


1 Answers

I would consider adding window.listen() before setting up the key bindings for the move_right()

window.listen()
window.onkeypress(move_right, 'Right')
like image 91
GGC ORLY Avatar answered Oct 24 '25 02:10

GGC ORLY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!