Mailing List Archive

Tkinter and classes
Hi all. I'm just fiddling about with Tkinter buttons and labels trying
to get the text in a Label to change when I press a button, this is
essentially what I've done:


class Helloworld:
def __init__(self, master):
_lblstr = StringVar()
_lblstr.set("hello world")

frm = Frame(master)
frm.pack()

but = Button(frm, text='Hello!', command=setLabel)
but.grid(row=0)

lbl = Label(frm, textvariable=_lblstr)
lbl.grid(row=1)

def setLabel(self):
_lblstr.set("HELLO WORLD!!")

This will run, but barfs out on the callback.
Am I misunderstanding the relationship between the callback to the
namespace of the class?

Thanks!

Justin
Tkinter and classes [ In reply to ]
Justin Muir <jkmuir@uniserve.com> wrote:

> class Helloworld:
> def __init__(self, master):
> _lblstr = StringVar()
> _lblstr.set("hello world")

> frm = Frame(master)
> frm.pack()

> but = Button(frm, text='Hello!', command=setLabel)
> but.grid(row=0)

> lbl = Label(frm, textvariable=_lblstr)
> lbl.grid(row=1)

> def setLabel(self):
> _lblstr.set("HELLO WORLD!!")

> This will run, but barfs out on the callback.
> Am I misunderstanding the relationship between the callback to the
> namespace of the class?

Try replacing _lblstr by self._lblstr to make it an instance variable.

As you programmed it above _lblstr is just local to the __init__ function
and disappears as soon as the function is finished. So setLabel doesn't
know anything about a _lblstr.

Cheers, Frank

--
"I think we have different value systems." "Well mine's better." "That's
according to your ... oh never mind."
-- Douglas Adams, 'Mostly Harmless'
Tkinter and classes [ In reply to ]
Thanks for the responses! They were timely and informative.

Again, thank you !


Justin.