How to bind some variable value in tcl/tk?

323 Views Asked by At

Let say we have some variable x, initially x=0.
Whenever x changes its values from 0 to 1, click some button A
Whenever x changes its values from 1 to 2, click some button B
Whenever x changes its values from 2 to 0, click some button C
...

How to do that ?

1

There are 1 best solutions below

0
On BEST ANSWER

Here's a simple example that updates x once a second and uses a trace on the variable to invoke a button press when it's updated, with the specific button depending on the new value.

#!/usr/bin/env wish

grid [ttk::button .a -text A -command {puts "Buttom A pushed"} -state active]
grid [ttk::button .b -text B -command {puts "Button B pushed"}]
grid [ttk::button .c -text C -command {puts "Button C pushed"}]

set x 0

proc update_gui {name _ _} {
    upvar $name v
    switch -- $v {
        0 { .c state !active; .a state active; .a invoke }
        1 { .a state !active; .b state active; .b invoke }
        2 { .b state !active; .c state active; .c invoke }
    }
}

proc update_x {} {
    variable x
    set x [expr {($x + 1) % 3}]
    after 1000 update_x
}

trace add variable x write update_gui
after 1000 update_x