Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tcl/tk Button - How I can pass a variable on the command option?

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.

like image 603
milarepa Avatar asked Jan 21 '13 22:01

milarepa


2 Answers

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]
like image 67
glenn jackman Avatar answered Oct 20 '22 02:10

glenn jackman


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"
like image 41
Chpock Avatar answered Oct 20 '22 02:10

Chpock