pythonturtle-graphics

Python turtle not moving on arrow press


I am trying to make my turtle (main_ship) move across the bottom of my screen according to when the user presses the left and right arrow keys but the turtle is not moving. I have used the same code before when making Pong so I'm not sure why it's not working.

import turtle

wn = turtle.Screen()
wn.title("Game")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

main_ship = turtle.Turtle()
main_ship.speed(0)
main_ship.shape("turtle")
main_ship.color("green")
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.penup()
main_ship.goto(0, -290)
main_ship.left(90)

def main_ship_right():
    x = main_ship.xcor()
    x += 20
    main_ship.setx(x)
def main_ship_left():
    x = main_ship.xcor()
    x -= 20
    main_ship.setx(x)

while True:
    wn.update()
    wn.mainloop()

    wn.listen()
    wn.onkeypress(main_ship_right, "Right")
    wn.onkeypress(main_ship_left, "Left")

When I press the arrow keys, nothing happens but the code still runs and there are no error messages.


Solution

  • You have to assign keys before mainloop() which runs all time till you close window.

    You don't need while True because mainloop() already runs internal loop.

    You may have to remove wm.tracer(0) or you will have to run wn.update() to refresh elements in window.

    import turtle
    
    # --- functions ---
    
    def main_ship_right():
        x = main_ship.xcor()
        x += 20
        main_ship.setx(x)
        wn.update()
    
    def main_ship_left():
        x = main_ship.xcor()
        x -= 20
        main_ship.setx(x)
        wn.update()
    
    # --- main ---
    
    wn = turtle.Screen()
    wn.title("Game")
    wn.bgcolor("black")
    wn.setup(width=800, height=600)
    wn.tracer(0)
    
    main_ship = turtle.Turtle()
    main_ship.speed(0)
    main_ship.shape("turtle")
    main_ship.color("green")
    main_ship.shapesize(stretch_wid=2, stretch_len=4)
    main_ship.penup()
    main_ship.goto(0, -290)
    main_ship.left(90)
    wn.update()
    
    wn.listen()
    wn.onkeypress(main_ship_right, "Right")
    wn.onkeypress(main_ship_left, "Left")
    
    wn.mainloop()