Main Content

Error: Cant read xxxxx: no such variable (in Tcl Tk)

Archive - Originally posted on "The Horse's Mouth" - 2009-02-14 04:06:03 - Graham Ellis

If you set a Tcl (Tcl/Tk) variable within a proc, or within the callback command of a widget, that variable does not exist at run time until you have run the proc or callback procedure, or until you have initialised the variable in some other way.

Let's see a Tk example. I have created a window with two buttons. The one labelled "Press me first" creates a variable called pressed than contains the value hello. And the one labelled "Press me second" updates the label called .report with the value that's stored in the variable.


If you run the program , pressing the first button first, and the second button second, it works as illustrated at the top of this entry to the left and right.

But if you press the button labelled press me second without pressing the button labelled press me first, you get this:



Here is the complete code that I used to generate these examples:

button .demo1 -text "Press me first" -command {
  global pressed
  set pressed hello
  }
button .demo2 -text "Press me second" -command {
  global pressed
  .report configure -text $pressed
  }
button .quit -text exit -command exit
label .report -text "---"
pack .demo1 .demo2 .report .quit


What should you do if you are getting a message such as "Error: Can't read 'pressed': no such variable"?
• check your logic
• if necessary, initialise the variable outside your callbacks
• check that you have used global if necessary (in order to share a variable from within a proc with the same variable of the same name in the main code)
• send me an email to say you found this article useful!

We run regular public Tcl and expect courses and Tcl/Tk and wish courses. For a full schedule of all of our public courses, see here




This short article was written in response to an emailed question. I answered:

It looks like you are trying to use the contents of a variable before you set it - remember that variables in Tcl are only created when you actually run the code that sets them, so a definition within a proc will only cause the variable to be created when the proc is actually run.

Your question is a very good one, and you have provided inspiration for a full example on my blog - see:

http://www.wellho.net/mouth/2040_Error-Cant-read-xxxxx-no-such-variable-in-Tcl-Tk-.html


Graham