Search code examples
variableswidgettcl

replacing a tcl variable that is already loaded on widget window


I need some help to replace one variable that is already loaded on a toplevel/window widget. I have a toplevel (.), with the title:

set USER "Adam" 

wm title . "Main Menu - WELCOME $USER!"

and the variable USER is loaded when starting the program.

if i use:

set USER John

How can i replace the $USER value, or update the entire widget, to show John instead Adam.

Thank YOU!!

I tried the command trace but didn't worked.


Solution

  • The trace command is exactly how you detect that a variable (usually at the global or namespace level; tracing local variables is supported but not usually a good idea and very expensive computationally) has changed. It's just that you need to set it up right. By far the easiest way is to use a procedure for the callback:

    proc USERchanged {args} { # We can ignore the arguments; we know what's happened
        global USER
        wm title . "Main Menu - WELCOME $USER"
    }
    
    trace add variable USER write USERchanged
    

    You can also use a lambda term or method call, but the syntax is a bit more complex. Here's a lambda:

    trace add variable USER write [list apply {args {
        global USER
        wm title . "Main Menu - WELCOME $USER"
    }}]
    

    Note the use of list to build the actual callback.


    Technically you can put a script directly in the callback, but this is not recommended as it is easy to get wrong and awkward/annoying to debug. Use a procedure instead.

    trace add variable USER write {wm title . "Main Menu - WELCOME $::USER"; #}