4

I'm trying to add keyboard input to move python's turtles but without even pressing the assigned key the turtle moves as if I'm holding the assigned key.

What am I doing wrong?

My code is below:

# import
import turtle

# init screen, turtle
window = turtle.Screen()
turt = turtle.Turtle()
turt.speed(5)

def up():
    turt.forward(10)
def left():
    turt.left(10)
def right():
    turt.right(10)

while True==True:
    turtle.onkey(up(), "Up")
    turtle.onkey(left(), "Left")
    #turtle.onkey(right(), "Right")

# window await
turtle.listen()
window.mainloop()
ggorlen
  • 44,755
  • 7
  • 76
  • 106
jll123567
  • 85
  • 7

2 Answers2

4

Rather than calling screen.onkey(function(), "key") you call screen.onkey(funtion, "key")

So

turtle.onkey(up(), "Up")

becomes

turtle.onkey(up, "Up")
jll123567
  • 85
  • 7
  • 1
    yea, when you pass a function as an arg, such as in that case, it's what they refer to as a "callback function" or simply a "callback" -- https://en.wikipedia.org/wiki/Callback_(computer_programming) – Doyousketch2 May 18 '21 at 11:22
2

In addition to @jll123567's excellent suggestion (+1) about passing, instead of calling, the event handler functions, you need to get rid of the while True==True: loop and move its content up a level. An infinite loop like this keeps listen() and mainloop() from getting called so your events never get registered, nor handled. A complete solution:

from turtle import Turtle, Screen

def up():
    turtle.forward(10)

def left():
    turtle.left(10)

def right():
    turtle.right(10)

# init screen, turtle
screen = Screen()

turtle = Turtle()
turtle.speed('normal')

screen.onkey(up, 'Up')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')

screen.listen()
screen.mainloop()
cdlane
  • 40,441
  • 5
  • 32
  • 81