MJ - The following is a work in progress. I couldn't find a good event tutorial starting from basics anywhere. If this exists please include a link.
A Tcl event tutorial
The goal of this page is to give an introduction to the Tcl eventloop suitable for Tcl beginners. If you make changes to this page please keep that in mind.
Assumptions, it is assumed that you are reasonably versed in Tcl. This means that you should know:
If you don't know this it is better to start with a generic Tcl tutorial first (links here)
What is event based programming
When you write an console based application and you don't use events. The commands in your script will be executed in a specific order. For example the script:
set a 1 set b 2 puts $a puts $b
will:
For a large class of applications this is not a limitation and you can get a long way without ever needing events.
Now imagine you write an application that takes user input and based on that user input takes a certain action. For instance you have a currency conversion application where the user can change the currency to convert from, the currency to convert to and the amount to convert. One way to write this is like:
However if you want to allow the user to take actions in a more random order this will be fairly limited and you might arrive to something more like:
while 1 { show_menu gets stdin input switch $input { # do different things based on user input } }
This show the beginnings of a rudimentary event loop. The system is waiting for an event (the user presses a key) and takes an appropriate action (execute the correct switch case) or to make the correspondance even clearer:
while 1 { show_menu gets stdin event switch $event { # do different things based on the user input event } }
When you start building GUIs it is even more clear that you will need to act on events, because the user has a very large number of possible actions he can perform at any given moment in time. Think about:
If all of these actions generate events and we have some way of reacting to these events we can take the correct action based on what the user does without knowing when he will do it (e.g. he might enter some text first and then press a button or vice versa)
How does Tcl use event based programming
Events in Tk
Common pitfalls when using events in Tcl