Tcl / tk button. How to pass a variable in a command?

I have a problem passing variables to command options, 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 that when button.0 is called, at that moment it takes a variable value that is 1.

I understand that to achieve the desired results, I can use the procedure and the global variable, but I would like to know if this can be achieved without resorting to calling the procedure.

Thanks in advance.

+4
source share
2 answers

If you want to substitute the current value of a variable when defining a callback, you need to use a different citation mechanism:

 button .button.$count -text $count -command [list puts $count] 
+6
source

Using the code, you create two buttons that launch the command:

 puts $count 

In your example, when you press the button, the variable $ count is "1", so it "puts" and displays this value. For proper operation, you need to create 2 buttons. The first button command should be "puts 0". The second button command should be "puts 1". We must apply the replacement when creating the button. For instance:

 -command [list puts $count] -command "puts $count" 
+3
source

All Articles