[Tutor] Tk variable problem

Alan Gauld alan.gauld at blueyonder.co.uk
Sat Aug 7 00:13:18 CEST 2004

OK Thats a bit esier to read. I've commented the code below:

> > You also seem to have two calls to mainloop(), that usually
> > Tkinter... It certainly confuses me!
> It is on two different tab spacings. Does that still confuse

It will when the second one gets called!

> >> def preferanser():
> >>    def die(event):
> >>        root.destroy()
> >>    def bildekatalog():
> >>        bildedir =
> >>        print bildedir
> >>        blabel = Label(root)
> >>        xx = StringVar(root)
> >>        xx.set("Bildekatalog:\n" + bildedir)
> >>        blabel["text"] = xx.get()
> >>        blabel.pack()
> >>        root.mainloop()

I'm assuming the lines below here were not really intended to be
part of the fuction definition above(preferanswer())?
Even if they were I'd suggest you are better making all
your function definitions top level ones. Otherwise the
functions you define go out of scope when the top function
completes and it all gets a bit confusing IMHO.

So I've repasted them as separate functions:

# this event handler never actually gets used because we dont set it
def die(event):

# this event handler gets called when the button gets pressed.
def bildekatalog():
    # first we get the new value
    bildedir = tkFileDialog.askdirectory(initialdir='c:/bilder/')
    print bildedir  # and print it on the console window for debugging
    # now we repeat all the initialisation code thus creating
    # a duplicate set of controls! So comment them out:
    # xx = StringVar(root)
    # xx.set("Bildekatalog:\n" + bildedir)
    # blabel = Label(root)
    # blabel["text"] = xx.get()
    # blabel.pack()
    # and just set the text property of the Label directly.
    blabel["text"] = bildedir

root = Tk()   # start the Tk ball rolling

xx = StringVar(root)   # create a string and initialise it.
# but we can't use bildedir cause it doesn't exist here!
xx.set("Bildekatalog:\n" + bildedir)

blabel = Label(root)   # crate a Label widget and set parameters
blabel["height"] = 10
blabel["width"] = 30
blabel["text"] = xx.get()

# easier to do the above with:
blabel = Label(root, height=10, width=30, text=xx.get() )
blabel.pack(side=LEFT)  # make it visible

# now for the button which calls the function...
b = Button(root, text="Endre", width=10, command=bildekatalog)
b.pack(side=RIGHT, padx=40, pady=15)

root.mainloop()   # call it once at the outermost level.


Alan G

More information about the Tutor mailing list