Version 1 of Event programming and why it is relevant to Tcl/Tk programming

Updated 2000-09-11 18:25:24

Purpose: explain the fundamentals of event programming for someone new to the concept.


Many modern programming tasks involve the integration of things that happen asynchronously; they do not happen at precisely controlled times and the computer has to be prepared to deal with whatever happens in the order that it happens.

For example, in a GUI you don't want to force a user to press a button between each move of the mouse, and in a network server with two clients connected you definitely do not want to force one client to wait for the other to do something (unless you're doing something collaborative of course! :^)

The most commonly used technique for doing this is called event-based programming, and it is such a good coding idiom that it is used in nearly every practical programming language in use today. Of course, some languages offer better support for it than others...

The basic idea is that you have a queue of possible events, and as the environment (i.e. the world outside the program) does things, so events are generated and added to the queue. Meanwhile, the program sits there, grabbing events off the queue and doing whatever it takes to deal with them, usually by way of a gigantic [switch] statement (or whatever that language's equivalent is.)

Luckily, Tcl comes with all this support built in already. All it takes to turn it on is to set up some event handlers and to start accepting events using the [vwait] command. In Tk, things are even easier as the library sets up a load of handlers anyway, and also starts up the event loop once it has evaluated your startup script.

People who aren't used to event-driven programming often have a hard time getting started. See Countdown program for a simple example of converting a loop-based program to an event-driven one.


Major classes of event in Tcl/Tk

  • GUI events - Tk's raison d'etre. Note that this includes [send] and various [wm] subcommands as well as [bind] and the -command options to various widgets...
  • File events - These occur when it becomes possible to either read from or write to a channel (especially to a pipe, socket or serial port.)
  • Timer events - Great for scheduling things for happening later, and brilliant for use with periodic activity.
  • Idle events - Useful for when you wish to put something off until there is nothing to do except wait for events (mainly used in the management of display updates...)

There are also conditions that are internal to a program that can be best thought of as being events:

  • Variable accesses
  • Background error handling
  • Unrecognised command handling