Event-Driven Programming is Fun!

Functions in Python can be used for many different purposes. Another purpose is to implement event-driven programs.

This program is event-driven since it responds to mouse clicks and keys being pressed on the keyboard.

The Etch-A-Sketch is fun because you get to see how event-driven programming works and at the same time, you get to be creative in testing it and deciding what new features you might add.

If you like, you can incorporate more complex shape drawing in this program. For instance, in the last lesson, students learned to draw a house. In this program, you could draw a house at the current location everytime the letter "h" is pressed.

There are many other possible extensions to this program that could be added. Give the students some time to be creative and see what they come up with!

Event-Driven Programming

In the last lesson we learned that functions give us quite a bit of power and flexibility in our programs. Given what we know about functions, event-driven programs can be written without too much trouble.

An event-driven program is a program that responds to events. Usually, these events are generated from user input via the keyboard or mouse in a Graphical User Interface (GUI) environment. A GUI program has one main loop called the event loop that looks for the next mouse or keyboard event and then dispatches that event by calling an event handler. When we write an event-driven program we provide the event handlers. Turtle graphics supports event-driven programming by allowing us to provide a mouse handler and keyboard handlers.

Consider writing an Etch-A-Sketch program. Let's say we want to write it so that when we push the up arrow on the keyboard we want to draw an arrow going up. Here is what that code looks.

The program above creates a Turtle, hides the turtle, and then sets up three event handlers. The mouseHandler makes the turtle go wherever you click the mouse. The upHandler responds to the up arrow being pressed. The colorHandler responds to the letter c being pressed and changes the drawing color to red.

Now You Try It

Using this program as a template, write an Etch-A-Sketch program that allows you to do the following.