Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 26.  Binding Commands to Events

Event Sequences

The bind command accepts a sequence of events in a specification, and most commonly this is a sequence of key events. In the following examples, the Key events are abbreviated to just the character detail, and so abc is a sequence of three Key events:

bind . a {puts stdout A}
bind . abc {puts stdout C}

With these bindings in effect, both bindings are executed when the user types abc. The binding for a is executed when a is pressed, even though this event is also part of a longer sequence. This is similar to the behavior with Double and Triple event modifiers. For this reason you must be careful when binding sequences. You can use break in the binding for the prefix to ensure that it does not do anything:

bindtags $w [list $w Text [winfo toplevel $w] all]
bind $w <Control-x> break
bind $w <Control-x><Control-s> {Save ; break}
bind $w <Control-x><Control-c> {Quit ; break}

The break ensures that the default Text binding that inserts characters does not trigger. This trick is embodied by BindSequence in the next example. If a sequence is detected, then a break binding is added for the prefix. The procedure also supports the emacs convention that <Meta-x> is equivalent to <Escape>x. This convention arose because Meta is not that standard across keyboards. There is no meta key at all on Windows and Macintosh keyboards. The regexp command is used to pick out the detail from the <Meta> event.

Example 26-3 Emacs-like binding convention for Meta and Escape.
proc BindSequence { w seq cmd } {
   bind $w $seq $cmd
   # Double-bind Meta-key and Escape-key
   if [regexp {<Meta-(.*)>}$seq match letter] {
      bind $w <Escape><$letter> $cmd
   # Make leading keystroke harmless
   if [regexp {(<.+>)<.+>}$seq match prefix] {
      bind $w $prefix break

The use of break and continue in bindings is not supported in Tk 3.6 and earlier. This is because only a single binding tag can match an event. To make a prefix of a sequence harmless in Tk 3.6, bind a space to it:

bind $w $prefix {}

This installs a binding for the widget, which suppresses the class binding in Tk 3.6. The space is different than a null string, {}. Binding to a null string deletes the current binding instead of replacing it with a harmless one.

      Previous section   Next section