I have a problem passing variables on the command option, for example:
package require Tk
wm withdraw .
destroy .button
toplevel .button
# button.0: puts 0
set count 0
button .button.$count -text $count -command {puts $count}
grid .button.$count -column $count -row 0
# button.1: puts 1
incr count
button .button.$count -text $count -command {puts $count}
grid .button.$count -column $count -row 0
However button.0 puts 1 instead of 0. It seems when the button.0 is called it takes the value of the variable at that moment which is 1.
I figure it out that I can use a procedure and a global variable to achieve the desire results, but I would like to know if it is possible to achieve this without resorting to a procedure call.
Thank you in advance.
If you want to substitute the current value of the variable when you define the callback, you need to use a different quoting mechanism:
button .button.$count -text $count -command [list puts $count]
With your code you create 2 buttons that trigger command:
puts $count
In your example, when you push button a variable $count is equal to "1", so "puts" and displays this value. For proper operation of the need to create 2 buttons. A first button command should be "puts 0". A second button command should bіt "puts 1". We must apply the substitution when creating the button. For example:
-command [list puts $count]
-command "puts $count"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With