← Python functions and events

Events

Make a program wait, then react when something happens.

Every app you use is waiting: for a tap, a key or a timer. Code runs when an event happens, not from top to bottom.

Until now your program ran from the top to the bottom and stopped. Programs with a user interface do not work like that. They wait, and run a function when something happens. That function is called a callback.

In these examples, click the picture once before using the keyboard, and press Stop when you are done.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

events.py
from turtle import *

speed(0)
penup()


def stamp(x, y):
    goto(x, y)
    dot(30, "orange")


onscreenclick(stamp)
listen()
mainloop()

onscreenclick(stamp) hands the function over by name. The program then waits in mainloop(), and each click runs stamp with the place you clicked.

What happens when you click on the picture?

RunRun it and compare the result with your prediction.

Run

Run it, click around the picture, then press Stop and compare with your prediction.

events.py
from turtle import *

speed(0)
penup()


def stamp(x, y):
    goto(x, y)
    dot(30, "orange")


onscreenclick(stamp)
listen()
mainloop()
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

Look at how the keys work: each onkey pairs a function with a key.

events.py
from turtle import *

speed(0)


def go_up():
    setheading(90)
    forward(20)


def go_down():
    setheading(270)
    forward(20)


onkey(go_up, "Up")
onkey(go_down, "Down")
listen()
mainloop()

Say what each event line does.

Work out how often a handler runs.

Here is a version where something is wrong.

Match each line with what it does.

onscreenclick(stamp)
onkey(go_up, "Up")
ontimer(step, 50)
mainloop()

The program above is running. You press the Up arrow 5 times. How many times does go_up run?

This program should stamp a dot where you click, but it stops with an error. Click the wrong line.

ModifyChange the code on purpose and check the result.

Modify

Change the size and colour of the dot.

Need a hint?

The dot size is the first number in dot( ), and the colour is the word in quotes.

Make each click stamp a square.

Need a hint?

A square is four sides: a loop that moves forward and turns right 90.

Another hint

Put the loop inside stamp, after the goto.

Try it yourselfYour edits are saved in this browser.

Draw a square inside the click function.

    Run your program. This ticks when your code does all of the above.

    InvestigateTrace how each line of code connects to what you see.

    Mix it up

    Work this out on paper first.

    score = 0
    
    def add_point(x, y):
        global score
        score = score + 1
    
    onscreenclick(add_point)
    

    The student clicks the screen 5 times. What is score afterwards?

    MakeBuild something new using what you have learned. Expect a few tries; that is normal.

    Make

    Steer the turtle with the keys: Up moves forward 20, Left turns left 30 degrees, Right turns right 30 degrees.

    Try it yourselfYour edits are saved in this browser.
    Need a hint?

    Write three small functions, one for each key, then connect each with onkey.

    Another hint

    Left turns left 30 degrees: left(30). Right turns right 30.

    Steer with three keys.

      Run your program. This ticks when your code does all of the above.

      ModifyChange the code on purpose and check the result.

      Count the clicks

      Games and apps keep a score that changes when events happen. This program keeps score in a variable and shows it each time you click.

      The write(score, False, "left", ("Arial", 40, "normal")) line is a recipe: copy it whenever you want to show a value on the screen. The first part is what to write, and the last bracket sets the font and size.

      Behind the code: score is made outside the function. The line global score lets add_point change that same score. Without it, Python treats score inside the function as a new, empty name and stops with an error. Any handler that changes a variable from outside needs global.

      Make it count by 5 instead of 1, then make a key (r) that resets it to zero. Then add a timer: use ontimer to add a point every second.

      Try it yourselfYour edits are saved in this browser.
      For teachers

      Students write programs that wait for clicks, keys and timers, and run a function (a callback) each time something happens. About 50 minutes.

      Open the teacher guide: answers, solutions, slides and a worksheet.

      Students will be able to

      Before class

      Until now programs ran top to bottom and stopped. An event-driven program sets up what should happen, then waits (mainloop()). A callback is a function you hand over by name, which the computer runs for you later, every time the event happens. Try the stamp program: click the picture, then press Stop. Keys only work after the picture has been clicked once.

      Running the lesson

      1. Predict: the program reaches its last line, then waits. Ask what happens on a click, and why the program does not just end.
      2. Say it plainly: onscreenclick(stamp) means 'when someone clicks, run stamp'. Nothing runs until the event happens.
      3. Investigate: the bug task is the most common mistake. stamp() with brackets runs the function now, once, instead of handing it over.
      4. Modify: change what the function does, not the event line. That separation is the point.
      5. Make: three small functions, three onkey lines, then listen() and mainloop(). Remind students to click the picture before pressing keys.
      6. Counter: global score lets the function change the score made outside it. Read the Behind the code note together.

      The hard part (on purpose)

      Handing a function over (no brackets) instead of calling it. When the error appears, ask whether the line runs the function now or hands it over for later.

      When students get stuck

      Stretch and support

      Stretch: Add a timer that moves the turtle forward every half second, so it drives by itself while the keys steer it.

      Support: Give students the three key functions already written and ask them only to connect each one with an onkey line.

      Where it leads

      Next lesson builds a button from scratch: a drawn rectangle plus a click check. Every app waits for events: taps, keys and timers. Class ideas: a stamp painting the class designs together; steering a turtle through a maze drawn on paper; a timer-based animation.

      What each step is for

      Now you can
      Next lesson8. Build a buttonTurtle has no buttons, so build one from a rectangle and a click check.