Python: User input

Edited

If you are building a game with the turtle tool, you might want to have a way to detect user input. The turtle module has a few built-in ways to handle accepting user input for you.

The on_key Method

The on_key method allows you to define a function that you want to run when a certain key is pressed.

screen.onkey(function_name, "key")

The following code will cause the turtle to turn 90 degrees to the left whenever the left arrow key is pressed.

def turn_left():
    t.left(90)

screen.onkey(turn_left, "Left")

You will have to call screen.listen() in your code in order to start the process that listens for key events and reacts to them.

Here is the code to allow the user to turn a turtle with the right and left arrow keys and move forward with the up arrow key.

import turtle

screen = turtle.Screen()

t = turtle.Turtle()

def move_forward():
    t.forward(25)

def turn_left():
    t.left(90)

def turn_right():
    t.right(90)

screen.onkey(move_forward, "Up")
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")

screen.listen()