NameError 'self' not defined

Post here if you need help with creating a Graphical User Interface in Python.

NameError 'self' not defined

Postby Noob85 » Fri Dec 27, 2013 10:09 pm

Hi,

i've copied this script but it wont work.
Please tell me what is wrong with it.


Code: Select all
import wx


class Example(wx.Frame):
           
    def __init__(self, parent):
        # de window
        wx.Frame.__init__(self,parent)
        self.InitUI()
       
    def InitUI(self):
        self.SetBackgroundColour('white')
        self.SetSize((250, 200))
        self.SetTitle('Windowname')
        self.Centre()
        self.Show(True)
       
  #zet hier eigen objecten
    btn = wx.Button(self, label='Close', pos=(20, 120),
          size=(80, -1))
    btn.Bind(wx.EVT_BUTTON, self.OnClose)

       
    #zet hier eigen functies
    def OnClose(self, e):
        self.Close(True)

       
def main():
    # het standaard venster
    ex = wx.App()
    Example(None)
    ex.MainLoop()   

# als je opstart beginnen met de main functie
if __name__ == '__main__':
    main()


Code: Select all
Traceback (most recent call last):
  File "/home/pi/close.pyw", line 4, in <module>
    class Example(wx.Frame):
  File "/home/pi/close.pyw", line 19, in Example
    btn = wx.Button(self, label='Close', pos=(20, 120),
NameError: name 'self' is not defined
Last edited by micseydel on Fri Dec 27, 2013 11:08 pm, edited 1 time in total.
Reason: Code tags, lock, title change.
Noob85
 
Posts: 1
Joined: Fri Dec 27, 2013 10:03 pm

Re: NameError 'self' not defined

Postby micseydel » Fri Dec 27, 2013 11:11 pm

Please use code tags in the future. At the top of the list of posts there's a topic with post-etiquette instructions.

Where did you "copy" the code from? How did you do so? Copy-paste, visually, downloaded, or what?

Regardless of all that, it just looks like an indentation issue. You just need to indent the code using self to be inside the methods in which it's defined. Currently, you have it at the class level, instead of inside the method.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1369
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to GUI

Who is online

Users browsing this forum: No registered users and 2 guests