Version 1 of Bindings and why they are important

Updated 2000-06-14 09:57:39

Purpose: explain the Tk concept of bindings. List the different kinds of bindings available. Show a practical example of use.

Bindings are the connections between widgets that create events, and the code (procedures) that handle the events.

 proc makeButton { buttonName buttonText } {
    button .$buttonName -text $buttonText
    bind .$buttonName <Button-1> "$buttonText"
    bind .$buttonName <Button-2> "destroy .$buttonName"
    bind .$buttonName <Button-3> "puts \"$buttonText\""
    pack .$buttonName 

Bindings are a specialisation of the general concept of event handlers to Tk's external event mechanism, and they are needed because GUIs are asynchronous things; you don't know what a user is going to do next, and you have to handle a lot of different possibilities. The only alternative to the system of having events is to use a finite state machine, but writing one of those for a modern GUI is a terrifying concept!

Most system programming languages use callbacks to handle events, but in Tcl it is far more natural to directly nominate a piece of code to execute whenever a particular event arrives, especially as this can always call a procedure if needed. It is this code that is called a binding (because of the command used to manage this association; bind.)

But now for an example:

  pack [label .l -textvariable msg]
  set msg "Dum de dum de dum..."
  bind .l <Enter> {set msg "Hello friend"}
  bind .l <ButtonPress-1> {set msg "You're touching me!"}
  bind .l <ButtonRelease-1> {set msg "You've let go."}
  bind .l <Leave> {set msg "Dum de dum de dum..."}
  bind .l <3> {bell}