classes and wx python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • askalottaqs
    New Member
    • Jun 2007
    • 75

    classes and wx python

    i know everyone keeps saying that one needs to be using classes and not just functions, but so far i haven't had any problems with functions aside from the fact that everyone's using them and when i see the help in any of the forums it's all in classes form,

    my question is

    im working basically with wx python, mainly doing interfaces for applications and nothing too fancy, connecting small databases and what not,

    should i be migrating to classes? will it give me anything extra? i won't be using inheritance as i never saw it necessary in GUI's, but it keeps bothering me that i can't use the "self" thingy that everyone's using all around,

    if i should actually do that, if i already have like a 1000 line code now i;m working on, is there an easier way to migrate, and understand what's going on?

    i read a bunch of tutorials about classes, they're just plain confusing because i understand how they "hypothetically " be used in inheritance and all that, but i never really understand how i cld use it in daily life programming, especially with the level i;m working on,

    really appreciate any comments or answers,

    i just need to understand the whole fuss

    any examples of a use of classes with wx that actually lead to something would be really appreciated

    thanks

    T
  • Hackworth
    New Member
    • Aug 2009
    • 13

    #2
    """
    Okay, I'm not an expert with OOP myself, but I am a wxPython user and I do use classes. A very small sample code to work with for a bit of explanation. A simple class definition follows:
    Code:
    class MyObject(object):
        def __init__(self, argument):
            self.arg = argument
    The first line defines our class 'MyObject'. The value inside the parentheses is the object that our class inherits properties from. In current python style, I believe it is the practice to inherit from the sort-of default object type appropriately called 'object'. Remember that classes are objects, so you can specify a class to inherit properties from.

    First, we override the built-in function __init__. Note that the first argument is 'self'. The first argument in every function we define in a class should be self (for a much better explanation, hit the docs! :))

    This function gets called when the class is initialized (or is it called instantiated..? ) along with any arguments. Thus it is usually a good starting place to get things done. Now, we set the passed argument to 'self.arg' this makes the attribute 'arg' accessible via self.

    I'm going to add a few things to our code and give you an example, then I promise I will relate this to wxPython!
    Code:
    class MetaObject(object):
        def __init__(self):
            print "This is MetaObject!"
    
    class MyObject(MetaObject):
        def __init__(self, argument):
            # We need to initialize the class we are inheriting from.
            MetaObject.__init__(self)
    
            # Set our attribute.
            self.arg = argument
            print " - This is MyObject!"
    
        def print_arg(self):
            print " - Argument was: %s." % self.arg
        
    # Create an instance of our class MyObject.
    MyObj = MyObject(0)
    # Accessing a method.
    MyObj.print_arg()
    # Changing an attribute.
    MyObj.arg = "New arg!"
    print MyObj.arg
    If you run this, it would produce this output:

    This is MetaObject!
    - This is MyObject!
    - Argument was: 0.
    New arg!

    Does this make sense? Let's look at it as applied to wxPython.

    It's important to note that there are many uses and applications for classes these are just a couple of (I think) relevant examples. I often find the need for creating my own dialogs and classes are a perfect solution. What I do is create a class and have it inherit from the wx.Dialog class. Then in __init__ I initialize wx.Dialog and then go about setting up my dialog. Here's an example from a project of mine.
    Code:
    class EditDialog(wx.Dialog):
        """The Edit Dialog."""
        def __init__(self, parent, ID, title, pos=wx.DefaultPosition, \
                     size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, \
                     data=("","")):
            """Init the edit dialog."""
            wx.Dialog.__init__(self, parent, ID, title, pos, size, style)
            self.txtKey = wx.TextCtrl(self, -1, data[0])
            self.txtValue = wx.TextCtrl(self, -1, data[1], style=wx.TE_MULTILINE)
            self.lblKey = wx.StaticText(self, -1, "Key", size=(50, 15), \
                                        style=wx.ALIGN_RIGHT)
            self.lblValue = wx.StaticText(self, -1, "Value", size=(50, 15), \
                                          style=wx.ALIGN_RIGHT)
    
            st = wx.StaticText(self, -1, " ")
    
            edit_sizer = wx.BoxSizer(wx.VERTICAL)
            h_sizer = wx.BoxSizer(wx.HORIZONTAL)
            h_sizer.Add(self.lblKey, 0, wx.RIGHT, 4)
            h_sizer.Add(self.txtKey, 1, wx.EXPAND)
            edit_sizer.Add(h_sizer, 0, wx.EXPAND | wx.ALL, 1)
    
            h_sizer = wx.BoxSizer(wx.HORIZONTAL)      
            h_sizer.Add(self.lblValue, 0, wx.RIGHT, 4)
            h_sizer.Add(self.txtValue, 1, wx.EXPAND)
            edit_sizer.Add(h_sizer, 1, wx.EXPAND | wx.ALL, 1)
    
            btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
            st = wx.StaticText(self, -1, " ")
            btn_sizer.Add(st, 1, wx.EXPAND, 0)
            btn_okay = wx.Button(self, wx.ID_OK)
            btn_cancel = wx.Button(self, wx.ID_CANCEL)
            btn_sizer.Add(btn_okay, 0)
            btn_sizer.Add(btn_cancel, 0)
    
            edit_sizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 1)
            self.SetSizer(edit_sizer)
            self.Bind(wx.EVT_BUTTON, self.OnOk)
    
        def OnOk(self, evt):
            """End dialog with the corresponding ID."""
            self.key = self.txtKey.GetValue()
            self.value = self.txtValue.GetValue()
            self.EndModal(evt.GetId())
    This is a simple Dialog containing two TextCtrls and their corresponding StaticText labels with 'OK' and 'Cancel' buttons at the bottom. Users can edit the values. OnOk() is the function to look at. It ends the Dialog by callingEndModal () and passing it the argument that identifies the button that was clicked.

    And the corresponding code that utilizes this class might look like this:
    (from another class..)
    Code:
    def EditItem(self, key, value):
        """ Display the edit dialog. """
        dlg = EditDialog(self, -1, "Edit key/value..", data=(key, value))
        if dlg.ShowModal() == wx.ID_OK:
            data = (dlg.key, dlg.value)
    This is just an example function but hypothetically it would be called from some other piece of code and sent two arguments, key and value. We instantiate our custom Dialog sending it the required wx arguments and our argument 'data' which is a tuple containing 'key' and 'value'. The next line is where our Dialog gets shown with dlg.ShowModal() and if the 'OK' button was clicked, we set the variable 'data' to the values of the Dialog's attributes 'key' and 'value' which we set in the method OnOk(). So we displayed our dialog, and allowed the user to edit some values and then retrieved those values. (Although the example doesn't do
    anything very interesting with this..)

    Now we have a custom wx.Dialog! I'm sure you can see how useful this is as you can apply the concept to any widget and non-widgets alike!

    Another big, big benefit of using classes is being able to more efficiently reuse code. If you have been using wxPython then you have been using classes the entire time! Everytime you make a frame and change its properties and use its methods you are interacting with a class. The difference here is we are using that mechanism to our advantage and defining behavior ourself!

    I really hope that this was coherent and that it answers some questions and helps you along in your code. In my experience I felt it took me a long time, and several attempts to truly start to understand OOP and classes. I think you will find them extremely helpful in your wx
    programming, I know I do.

    If you need any clarification, please ask! The best resources you have are the python/wxpython docs and the wxPython demo. Use them!

    Comment

    • askalottaqs
      New Member
      • Jun 2007
      • 75

      #3
      thank you so much for all this information!

      it took me a while to read and really understand what's going on, and i think i understand a bunch of it, but here come my clarification questions..,

      # def __init__(self, parent, ID, title, pos=wx.DefaultP osition, \
      # size=wx.Default Size, style=wx.DEFAUL T_FRAME_STYLE, \
      # data=("","")):
      # """Init the edit dialog."""
      # wx.Dialog.__ini t__(self, parent, ID, title, pos , size, style)

      so the initializer which contains all the text boxes and stuff would be just one of the functions inside that class? no different? aside from the fact that it is the all mighty __init__?

      so comes another question, in the app that i would have, the main frame that would initialize the app would be the highest class under which everything resides? or would it be a stand alone class? and how would i call this main frame app? define an instance and simply call it? (in the demo, it shows the code but not how it was called) unless it was this part? because i still can't understand it :S

      Code:
      if __name__ == '__main__':
          import sys,os
          import run
          run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

      i know the fact that everytime i'm using a frame or dialog, i am accessing the class itself and manipulating its values, but i still feel i can still do that with having the dialog as a function to which i define the values of a dialog inside, and i think that is because i did not come across an example where a function will not do the job and i need a class instead, and until that happens, i wont really get it (with the example you've mentioned, isn;t it possible to define it in a function and call the function?)

      now i know i need to move to classes, in order to understand what i;m missing, so i have a very lame question here, has anyone made a tool to convert from functions to classes? because i really feel the difference if very systematic,

      otherwise, i have already gone through 500 lines of code, is it worth making the move now manually? or should i just let it be since it basically works with almost no problems so far?

      im sorry if my reply seems very scattered, but that's kinda how my thoughts are working now,

      you;ve been of tremendous help! i bow before u sensei

      T



      EDIT: i understand how classes may come in handy as a data structure, to store watever inside and then access them and change values individually, but haven;t gotten it in any other way :S just thought i'd mentions this

      Comment

      • Hackworth
        New Member
        • Aug 2009
        • 13

        #4
        I think this should help. It is a small demo of wxPython using OOPish concepts.



        Code:
        #!/usr/bin/python
        import wx
        
        class MainFrame(wx.Frame):
            def __init__(self, parent, ID, title, pos=wx.DefaultPosition,
                         size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
                wx.Frame.__init__(self, parent, ID, title, pos, size, style)
        
                label = "Click the button and change this text!\n(Or use the Menu..)"
                # Initalize some controls..
                self.panel = wx.Panel(self, -1, style=wx.BORDER_SUNKEN)
                self.text = wx.StaticText(self.panel, -1, label,
                                          style=wx.ALIGN_CENTER | wx.ST_NO_AUTORESIZE)
                self.button = wx.Button(self.panel, -1, "Click me!")
                self.panel.SetBackgroundColour(wx.WHITE)
                
                # Initialize the menubar
                menubar = wx.MenuBar()
                self.menu = wx.Menu()
                self.menu.Append(101, "&Edit text..", "Edit text")
                self.menu.AppendSeparator()
                self.menu.Append(102, "&Close", "Close")
                menubar.Append(self.menu, "&Menu")
                self.SetMenuBar(menubar)
                
                # Initialize the statusbar
                self.CreateStatusBar()
                self.SetStatusText("")
        
                # Initialize the sizers and fill them
                sizer = wx.BoxSizer(wx.HORIZONTAL)
                st = wx.StaticText(self.panel, -1, "")
                sizer.Add(st, 1, wx.EXPAND, 0)
                sizer.Add(self.button, 0, 0, 0)
                st = wx.StaticText(self.panel, -1, "")
                sizer.Add(st, 1, wx.EXPAND, 0)
        
                st = wx.StaticText(self.panel, -1, "")
                vsizer = wx.BoxSizer(wx.VERTICAL)
                vsizer.Add(st, 1, wx.EXPAND, 0)
                vsizer.Add(self.text, 1, wx.EXPAND | wx.ALL, 4)
                vsizer.Add(sizer, 1, wx.EXPAND | wx.ALL, 4)
        
                self.panel.SetSizerAndFit(vsizer)
        
                # Bind our events.
                self.Bind(wx.EVT_BUTTON, self.OnButton)
                self.Bind(wx.EVT_MENU, self.OnMenu)
        
            def OnMenu(self, event):
                if event.GetId() == 101:
                    self.ShowEditDialog()
                else:
                    self.OnClose(event)
        
            def OnButton(self, event):
                if event.GetId() == self.button.GetId():
                    self.ShowEditDialog()
        
            def OnClose(self, event):
                self.Close()
        
            def ShowEditDialog(self):
                dlg = EditDialog(self, -1, "Edit the StaticText..")
                if dlg.ShowModal() == wx.ID_OK:
                    self.text.SetLabel(dlg.value)
                    self.SetStatusText("Label changed to \"" + dlg.value + "\".")
        
        class EditDialog(wx.Dialog):
            def __init__(self, parent, ID, title, pos=wx.DefaultPosition, 
                         size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
                wx.Dialog.__init__(self, parent, ID, title, pos, size, style)
        
                # Initialize some controls.
                self.text = wx.TextCtrl(self, -1, "")
                self.okay = wx.Button(self, wx.ID_OK)
                self.cancel = wx.Button(self, wx.ID_CANCEL)
        
                st = wx.StaticText(self, -1, "")
                label = wx.StaticText(self, -1, "Enter text:")
        
                hsizer = wx.BoxSizer(wx.HORIZONTAL)
                hsizer.Add(st, 1, wx.EXPAND, 0)
                hsizer.Add(self.okay, 0, wx.EXPAND, 0)
                hsizer.Add(self.cancel, 0, wx.EXPAND, 0)
        
                sizer = wx.BoxSizer(wx.VERTICAL)
                sizer.Add(label, 0, wx.EXPAND | wx.ALL, 4)
                sizer.Add(self.text, 0, wx.EXPAND | wx.ALL, 4)
                sizer.Add(hsizer, 0, wx.EXPAND | wx.ALL, 4)
        
                self.SetSizerAndFit(sizer)
                self.Bind(wx.EVT_BUTTON, self.OnButton)
        
            def OnButton(self, event):
                self.value = self.text.GetValue()
                self.EndModal(event.GetId())
        
        if __name__ == "__main__":
            app = wx.App(redirect=False)
            mainframe = MainFrame(None, -1, "wxPython OOP Demo", size=(225, 200))
            mainframe.Show()
            app.MainLoop()

        Comment

        • askalottaqs
          New Member
          • Jun 2007
          • 75

          #5
          thank you so much for your reply,

          but i dont think ill be using it because this the program is almost done, and it's basically working flawlessly,

          maybe if i start something new

          you've been of tremendous help my friend

          thank you sir Hackworth

          Comment

          Working...