[Tutor] NameError

wesley chun wescpy at gmail.com
Tue Sep 22 02:37:09 CEST 2009


On Mon, Sep 21, 2009 at 2:06 PM, Wayne <srilyk at gmail.com> wrote:
> On Mon, Sep 21, 2009 at 4:00 PM, kreglet <kreglet at gmail.com> wrote:
>>
>> I keep getting the following error and don't uderstand why:
>>
>> Traceback (most recent call last):
>>  File "/home/kreglet/bin/test.py", line 15, in btnStatclick
>>    btnStat.set_label("Pressed")
>> NameError: global name 'btnStat' is not defined
>>
>>
>> #!/usr/bin/env python
>>
>> import gtk
>> import sys
>>
>> class NewAppWindow(gtk.Window):
>>
>>    def btnStatclick(self, widget, data=None):
>>        #print status
>>        if self.status == True:
>>            btnStat.set_label("Not Pressed")
>>            self.status =False
>>            print self.status
>>        elif self.status == False:
>>            btnStat.set_label("Pressed")
>>            self.status =True
>>            print self.status
>
> btnStat isn't defined here. I think you should be declaring a self.btnStat
> in the __init__ method (which I usually put as the first function in my
> class - I'm honestly not sure if it makes a difference), and calling
> self.btnStat


pretty much what wayne suggested. you need to put the btnStat variable
into your instance's namespace, hence self.btnStat = ... instead of
just btnStat whose namemapping will disappear when __init__()
completes even though the object still exists -- it's just an extra
reference held somewhere else.

by stashing it away into the instance('s dictionary), you'll be able
to access it again in the btnStatclick() callback.

best wishes,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list