Tech With Tim Logo
Go back

Key Presses & Events

Events

The turtle module allows us to detect when the user has hit certain keys on the keyboard or moved/clicked the mouse. Whenever the user performs an action as such it is called an event. We can listen for events and trigger functions to run if we "hear" the event.

Key Presses

Our first step is to set up a few functions that we will call when certain keys are pressed.

import turtle
import random

def up():
    tim.setheading(90)
    tim.forward(100)

def down():
    tim.setheading(270)
    tim.forward(100)

def left():
    tim.set_heading(180)
    tim.forward(100)

def right():
    tim.setheading(0)
    tim.forward(100)

# Setting the heading of the turtle simply faces it a certain direction

To listen for events we type turtle.listen().

turtle.listen()

Now that we are listening for events we can check if certain ones have occurred.

import turtle
import random

def up():
    tim.setheading(90)
    tim.forward(100)

def down():
    tim.setheading(270)
    tim.forward(100)

def left():
    tim.set_heading(180)
    tim.forward(100)

def right():
    tim.setheading(0)
    tim.forward(100)

tim.listen()

tim.onkey(up, "Up")  # This will call the up function if the "Left" arrow key is pressed
tim.onkey(down, "Down")
tim.onkey(left, "Left")
tim.onkey(right, "Right")

tim.mainloop()  # This will make sure the program continues to run 

Mouse Events

Now that we can move the turtle around with the arrow keys we want to be able to change its color when we click the left mouse button and stamp it when we click the right.

First we must set up two more functions that will run when the mouse button is clicked.

colors = ["red", "blue", "green", "yellow", "black"]

def clickLeft(x, y):  # Make sure to have parameters x, y
    tim.color(random.choice(colors))

def clickRight(x, y):
    tim.stamp()

To see if the user has clicked the mouse button we can use turtle.onscreenclick().

import turtle
import random

def up():
    tim.setheading(90)
    tim.forward(100)

def down():
    tim.setheading(270)
    tim.forward(100)

def left():
    tim.set_heading(180)
    tim.forward(100)

def right():
    tim.setheading(0)
    tim.forward(100)

colors = ["red", "blue", "green", "yellow", "black"]

def clickLeft(x, y):  # Make sure to have parameters x, y
    tim.color(random.choice(colors))

def clickRight(x, y):
    tim.stamp()

tim.listen()

turtle.onscreenclick(clickLeft, 1)  # 1:Left Mouse Button, 2: Middle Mouse Button
turtle.onscreenclick(clickRight, 3) # 3: Right Mouse Button

tim.onkey(up, "Up")  # This will call the up function if the "Left" arrow key is pressed
tim.onkey(down, "Down")
tim.onkey(left, "Left")
tim.onkey(right, "Right")

tim.mainloop()  # This will make sure the program continues to run 
Design & Development by Ibezio Logo