User Interaction Jump to this section

This lesson shows how to respond to keyboard and mouse input so your drawings can be interactive.

Keyboard control Jump to this section

Use screen.onkey(handler, key) and screen.listen() to handle key presses.

import turtle

screen = turtle.Screen()
t = turtle.Turtle()

def go_left():
    t.left(30)

def go_right():
    t.right(30)

screen.onkey(go_left, 'Left')
screen.onkey(go_right, 'Right')
screen.listen()  # make the program begin listening for user input

Press the Left/Right arrow keys to rotate the turtle.

You can use values such as 'a', 'space', 'Return', and 'Up'.

Mouse clicks Jump to this section

Use onscreenclick(handler) to respond to mouse clicks. The handler receives the x,y coordinates.

import turtle

screen = turtle.Screen()
t = turtle.Turtle()

def move_to(x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()

screen.onscreenclick(move_to)

Click anywhere on the canvas and the turtle will move there.


Or don't lift the pen up and have the turtle draw a line to wherever you click:

import turtle

screen = turtle.Screen()
t = turtle.Turtle()

def move_to(x, y):
    t.goto(x, y)

screen.onscreenclick(move_to)

Combining input Jump to this section

You can combine keyboard and mouse handlers to create simple drawing apps (move with keys, draw with clicks).

Exercise Jump to this section

  • Build a simple etch-a-sketch: arrow keys move the turtle while it draws.