The (command bound to event) error

Intro

This is a quick little note regarding a common problem Tclers may see: Error strings which are blank apart from " (command bound to event)". It's one of those nasty errors in that it doesn't provide the developer any context to explain what in the code is actually triggering it.


Lars H: Is this how it appears in errorInfo, or is it the actual error result?

peterc: Yep, that's all ::errorInfo gives you with this particular error.


Cause

This error is typically seen in dialogs and is triggered when the dialog is closed by the user.

The cause is essentially the setting of values and such in -command or in event bindings:

 grid [button .b -command { 
  set a [someDialog]
  puts $a
  (... other code)
  }]

or:

 bind .b <Button-1> { 
  set a [someDialog]
  (... other code)
  }

Lars H: This may be what triggers the error, but what is it that makes Tcl consider it an error? It's probably an error in programming — the code is evaluated in the global context rather than, as the programmer might have expected, a local context, which means all variables set are global — but this as such cannot be what Tcl balks at, can it?


Solution

The best way to avoid this error is to simply ensure that all programming logic launched by -command and events are in the form of single procs:

 grid [button .b -command someProc]
 bind .b <Button-1> someProc

 proc someProc {} {
  set a [someDialog]
  (... other code)
  }]

A pleasant side-effect is your code becomes more readable too :-).


Lars H: Indeed. Furthermore, if you've done that and are still having trouble figuring out what event caused your command to be called, you can equip the proc with a dummy argument that lets the caller identify itself:

 proc someProc {{caller ""}} {
  set a [someDialog]
  (... other code)
  }]

 grid [button .b -command {someProc "Button .b -command"}]
 bind .b <Button-1> {someProc "<Button-1> event"}

These "Button .b -command" or "<Button-1> event" arguments will then be visible if you trace the execution of someProc.