Professional Documents
Culture Documents
TCL-TK Ansys Tip
TCL-TK Ansys Tip
TCL-TK Ansys Tip
Dear all,
Katherine's issue is one I've run across several times, so I used this as
an excuse to figure it out for myself once and for all. I thought others
might be interested, so I summarized a couple of things about it:
The Problem: When you create an entry in Tcl/Tk, you associate a Tcl
variable with it. The problem arises when you want to use that variable to do something
from within a proc (proc's are subroutines in Tcl) and the entry was made in a different
proc.
Build all your entry widgets in your main routine so they are global by default
(makes for messy code, but OK for simple things)
Simple way:
Just declare the variable as global in the procs that it is used in.
NOTE: You can not use global if you are using namespaces
The proper way to do this is to place your entire routine into a namespace
Once you have done that, any time you reference a variable that is shared
across proc's you prefix it with namespace::
This is the "right way" because you don't have to worry about overwriting
a global variable that someone else defined.
However, I hate typing namespace:: on everything so I have never
gotten used to using this method.
pack $t.msg
pack $t.entry
pack $t.okBut
proc doOK {} {
puts $exmp1::myVar
destroy $exmp1::t
}
}
#---------------------------------------------------------------------------
-----------------------
#---------------------------------------------------------------------------
-----------------------
proc bldIt {} {
global t myVar
label $t.msg -text "Enter Something" -padx 2m -pady 2m
entry $t.entry -relief sunken -textvariable myVar
button $t.okBut -text "OK" -command doOK
pack $t.msg
pack $t.entry
pack $t.okBut
}
proc doOK {} {
global t myVar
puts $myVar
destroy $t
}
set t .exmp2
catch {destroy $t}
toplevel $t
bldIt
#---------------------------------------------------------------------------
-----------------------
If you look closely at the last example, you will note that the widgets
are built in a proc. If you build your widgets in the main routine,
AND you don't use namespaces, you don't need the globals:
#---------------------------------------------------------------------------
-----------------------
set t .exmp2 catch {destroy $t}
toplevel $t
pack $t.msg
pack $t.entry
pack $t.okBut
proc doOK {} {
puts $myVar
destroy $t
}
#---------------------------------------------------------------------------
-----------------------
Eric
-------------------------------------------------------------------------
Eric Miller
Director, CAD &
Software Services
Phoenix Analysis &
Design Technologies
(480) 813-4884, x103
www.padtinc.com
-----------------------------------------------------------------