1

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Vahagn
  • 4,670
  • 9
  • 43
  • 72

2 Answers2

1

There is probably some fancier way to do it, but in my case when I need unique names, I just compose one out of time data, something like

set systemTime [clock seconds];
set myname [concat [clock format $systemTime -format %H%M%S] ".myext"]

Etc, etc. There are lot of different formatting possibilities.

It's not elegant, but I have it working on my stuff and it's useful, also if you need to keep a certain track of them.

JasonBourne
  • 165
  • 1
  • 3
  • 14
  • This will break if you generate more than one name in the same second, which is quite possible if you are doing this to generate window path names. – Colin Macleod Jan 15 '12 at 20:26
  • It's true. In my case, I do some further checking to make sure it is even more unique by appending some extra data at the end (should it be necessary). I guess it comes handy if you need to create unique names at a "user" speed (e.g., a gui), but not if you have them running at "program" speed (e.g., a loop, etc.) – JasonBourne Jan 16 '12 at 05:25
1

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
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • Be aware however that this creates a _subtle_ memory leak, of the unique component of the widget name itself. Yes, this sounds absolutely mad but it is real and it can be a problem if you've got a very long running program that creates many widgets over time. (All other schemes that create unique names will have the same leak too. The problem is that Tk interns pathname components for some bizarre reason!) – Donal Fellows Jan 15 '12 at 22:12