4
votes

I'm a complete beginner in the tcl/tk world, but I've tried to research this one on my own, and keep coming up empty.

I'm extending with a tcl/tk app that allows me to add code to spawn a child window and do what I need to in there. The problem is that when I spawn that window and try to set a default value for my entry widget, it always shows up empty.

I've since created an ultra simple demo app to replicate this:

#!/usr/local/bin/wish

set myvar1 "initial value 1"

entry .entry1 -textvariable myvar1
button .spawnchild -text "Spawn Child" -command "spawn_click"

pack .entry1 .spawnchild

proc spawn_click {} {
    set myvar2 "initial value 2"
    toplevel .lvl2
    entry .lvl2.entry2 -textvariable myvar2
    entry .lvl2.entry3 -textvariable myvar1
    pack .lvl2.entry2 .lvl2.entry3
}

As you can see, the first window contains an entry widget that has the default value "initial value 1" and it shows up properly. When I click the "Spawn Child" button the child window is created. As you can see it contains two stacked entry widgets. Each one has a default value, with the one on top using a default value that was created in it's own scope and the entry on the bottom using the default value in the main program's scope.

The problem is that the top entry field doesn't show it's default value for some reason while the bottom one does just fine.

Multiple Popup Windows

Can anyone please provide an explanation of this behavior and how to get the top entry widget to show it's default value properly?

EDIT

Thanks Andrew and schlenk, it appears this was a case of RTFM :) I tested your global suggestions and it worked as promised. Thanks for setting me straight!

2

2 Answers

5
votes

Read the documentation of the -textvariable option. The variable name must be a global (or fully qualified namespace) variable name, but your myvar2 variable is a local variable. So you set a different variable in your proc than is used by the textvariable switch.

An easy fix for your problem would be to write the proc like this:

proc spawn_click {} {
    global myvar2
    set myvar2 "initial value 2"
    toplevel .lvl2
    entry .lvl2.entry2 -textvariable myvar2
    entry .lvl2.entry3 -textvariable myvar1
    pack .lvl2.entry2 .lvl2.entry3
}

By explicitly declaring myvar2 as global scope, you would use the same variable in your -textvariable binding.

5
votes

myvar2 needs to be defined at the global level. Define spawn_click as follows:

proc spawn_click {} {
   global myvar2;  # myvar2 is a global variable

   set myvar2 "initial value 2"
   toplevel .lvl2
   entry .lvl2.entry2 -textvariable myvar2
   entry .lvl2.entry3 -textvariable myvar1
   pack .lvl2.entry2 .lvl2.entry3
}

and you should be good...

enter image description here