user-interfacetcltk-toolkitincr-tcl

How to generate unique names for Tk toplevel window paths?


I need a way to generate an unused name for Tk toplevel window paths, just like #auto does it for Itcl objects.

How can I do that? Maybe Tk has a similar utility?


Solution

  • When I need unique widget names, I use something like this:

    variable sequencecounter 0;   # Don't touch outside this code!
    proc unique {{parent ""}} {
        variable sequencecounter
        while {[winfo exists [set w $parent.w$sequencecounter]]} {
            incr sequencecounter
        }
        return $w
    }
    

    That's guaranteed to return a widget name that doesn't exist. (Tk is guaranteed to run single-threaded so you know there are no nasty race conditions.) Use it like this:

    set top [toplevel [unique]]
    set btn [button [unique $top] -text "Hi" -command { exit }]
    pack $btn