Search code examples
pythonwxpython

why can't I access the variable in my class. python


I created a panel in my main class. I then wanted to create a button that goes into the panel. I created a seperate class for the button called panel_in_button and set main in its parameters in hopes that I could inherit the panel in my main class and then use it in my panel_in_button class but for some odd reason my button won't show up when I run the program. The program runs fine with the exception of that. Help please. Here is the error I get but I dont think it has anything to do with why I can't access panel.

Warning (from warnings module): File "C:\Python27\GUI practice.py", line 19 app=wx.PySimpleApp() #This runs the program wxPyDeprecationWarning: Using deprecated class PySimpleApp.

import wx

class main(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "My window", size=(300, 200))
        panel=wx.Panel(self)

class panel_in_button(main):
    def __init__(self):
        button = wx.Button(main.panel, label="exit",pos=(130,10), size=(60, 60))
        self.Bind(wx.EVT_BUTTON, self.closebutton, button)
        self.Bind(wx.EVT_CLOSE, self.closewindow)

    def closebutton(self, event):
       self.Close(True)

    def closewindow(self, event):
        self.Destroy()

if __name__=="__main__":
    app=wx.PySimpleApp() #This runs the program
    frame=main(parent=None, id=-1)#Displays the program
    frame.Show()
    app.MainLoop()

Solution

  • You can't write the code that way. main is a class, not an instance of a class. You shouldn't call a class's method directly. Instead, you need to instantiate it and then call your object's method. No where in this code do you instantiate panel_in_button. Anyway, I don't recommend programming this way. Here's a cleaned up version:

    import wx
    
    class main(wx.Frame):
        def __init__(self,parent,id):
            wx.Frame.__init__(self,parent,id, "My window", size=(300, 200))
            panel=wx.Panel(self)
    
            button = wx.Button(panel, label="exit",pos=(130,10), size=(60, 60))
            self.Bind(wx.EVT_BUTTON, self.closebutton, button)
            self.Bind(wx.EVT_CLOSE, self.closewindow)
    
        def closebutton(self, event):
            self.Close(True)
    
        def closewindow(self, event):
            self.Destroy()
    
    if __name__=="__main__":
        app=wx.App(False) #This runs the program
        frame=main(parent=None, id=-1)#Displays the program
        frame.Show()
        app.MainLoop()
    

    This combines the two classes into one. I also replaced the reference to wx.PySimpleApp as that is deprecated. I would recommend you take a look at sizers instead of absolute positioning. Sizers are definitely worth the effort to learn.