Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

a small tk program problem 1

Status
Not open for further replies.

dotaliu

Technical User
Mar 25, 2008
15
CN
#!/usr/bin/wish
set aa 0
for {set i 1} {$i < 5} {incr i} {
set bt [button .$i -text $i]
bind $bt <Button-1> {
incr aa
$bt configure -text $aa
update
}
}

when I press button .1 .2 .3 .4 , only button .4 text change. why this happen ? and how to make button text change separately?
 
The problem, as it often is, is one of substitution order. Since your binding script is in curly braces ({}), the variable bt is not evaluated until the script is run. At that time, bt has it's final value, 4. To get around this, I put the binding script in a separate proc:
Code:
set aa 0
for {set i 1} {$i < 5} {incr i} {
     set bt [button .$i -text $i]
     [red]pack $bt[/red]
     bind $bt <Button-1> "chgT $bt"
}
proc chgT {bt} {
 incr ::aa
 $bt configure -text $::aa
}

Note that you left out the pack statement in your post, but I assume you had it in your script or you wouldn't have gotten the buttons at all.

_________________
Bob Rashkin
 
thanks Bong. I tried some other ways and found one below also work:
#!/usr/bin/wish
set aa 0
for {set i 1} {$i < 5} {incr i} {
set bt [button .$i -text $i]
pack $bt
bind $bt <Button-1> {
incr aa
%W configure -text $aa
update
}
}
change $bt configure -text $aa to %W configure -text $aa .I don't clearly understand the difference between "" and {} in bind command. Would you explain it.
 
Quotes ("") induce immediate variable substitution. So when the interpreter reads, set a "name = $b" and had previously encountered, say set b bong, then the line is immediately set in the stack as set a "name = bong"

If it were curly braces ({}), set a {name = $b}, it goes into the stack just like that. Later, say if you puts $a, the then current value of b (which may no longer be "bong") will be used for substitution.

_________________
Bob Rashkin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top