Search code examples
pythonwxpythonwxwidgets

WxPython attribute error, *my class* object has no attribute *my function*


Python 2.7

Ubuntu 12.04

My code is available here.

I'm trying to put together a base for myself to make creating wxPython apps easier, I'm using the set up of my last program as that base but it's not working properly.

The problem arises when I try to bind a button to a function, this is the same layout that has worked for me before but now when I try to start the program with the button and the bind in place I get this error:

AttributeError: 'my_panel' object has no attribute 'on_quit'

If I remove the bind the program launches.

What's going on?

I've looked at other questions regarding this and it seems that most of the time it's a typing error, I've looked but I cannot find one.


Solution

  • The on_quit method in your code is indented too far. It needs to be at the same indention level as the init function. This is what you have:

    def __init__(self, parent):
        """docstring for __"""
        wx.Panel.__init__(self, parent)
        self.frame = parent
    
        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        self.widget_sizer = wx.BoxSizer(wx.VERTICAL)
    
        self.text_object = wx.StaticText(self, -1, 'Example')
        self.button_object = wx.Button(self, -1, 'QUIT')
        self.button_object.Bind(wx.EVT_BUTTON, self.on_quit)
    
        self.widget_sizer.Add(self.text_object, 0)
        self.widget_sizer.Add(self.button_object, 0)
    
        self.main_sizer.Add(self.widget_sizer, 0)
    
    
        def on_quit(self, event):
            """docstring for on"""
            self.Close()
    

    This is what it should look like:

    def __init__(self, parent):
        """docstring for __"""
        wx.Panel.__init__(self, parent)
        self.frame = parent
    
        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        self.widget_sizer = wx.BoxSizer(wx.VERTICAL)
    
        self.text_object = wx.StaticText(self, -1, 'Example')
        self.button_object = wx.Button(self, -1, 'QUIT')
        self.button_object.Bind(wx.EVT_BUTTON, self.on_quit)
    
        self.widget_sizer.Add(self.text_object, 0)
        self.widget_sizer.Add(self.button_object, 0)
    
        self.main_sizer.Add(self.widget_sizer, 0)
    
    
    def on_quit(self, event):
        """docstring for on"""
        self.Close()
    

    Also note that "self.Close()" will not work. It should be self.frame.Close()