Style Guide for wxPython code

This is a little style guide for using wxPython. It's not the be-all and end-all of how wxPython code should be written, but what I've tried to capture is a way to write wxPython code that is clear and Pythonic. It was vetted on the wxPython-users mailing list, with very little disagreement.

Pythonic is partly defined by:

http://www.python.org/doc/humor/#the-zen-of-python

This is about how to use wxPython-specific classes and structure. For code formatting advice, particularly if you want to include it in the wxPython lib, see: http://wxpython.org/codeguidelines.php

1. Use import wx NEVER use from wx import * or the ancient from wxPython.wx import *.

2. Keyword arguments in constructors.

2b. Use *args and **kwargs when subclassing wx.Windows:

class MyPanel(wx.Panel):
    """This Panel does some custom thing"""
    def __init__(self, *args, **kwargs):
        """Create the DemoPanel."""
        wx.Panel.__init__(self, *args, **kwargs)

3. Don't use IDs. There is very rarely a good reason to use them.

4. Use the Bind() method to bind events:

5. Use Sizers!

6. wx.App() now has the same built in functionality as wx.PySimpleApp(),

7. Use separate, custom classes rather than nesting lots of wx.Panels in one class.

8. Use native Python stuff rather than wx stuff where possible:

9. Use docstrings, consistently.

10. Use the StdDialogButtonSizer with buttons using standard wx.IDs when subclassing dialogs to place the buttons correctly for the user's platform.

   1     okButton = wx.Button(self, wx.ID_OK, "&OK")
   2     okButton.SetDefault()
   3     cancelButton = wx.Button(self, wx.ID_CANCEL, "&Cancel")
   4     btnSizer = wx.StdDialogButtonSizer()
   5     btnSizer.AddButton(okButton)
   6     btnSizer.AddButton(cancelButton)
   7     btnSizer.Realize()

Example

   1 #!/usr/bin/env python2.4
   2 
   3 # I like to put the python version on the #! line,
   4 # so that I can have multiple versions installed.
   5 
   6 """
   7 
   8 This is a small wxPython app developed to demonstrate how to write
   9 Pythonic wxPython code.
  10 
  11 """
  12 
  13 import wx
  14 
  15 class DemoPanel(wx.Panel):
  16     """This Panel hold two simple buttons, but doesn't really do anything."""
  17     def __init__(self, parent, *args, **kwargs):
  18         """Create the DemoPanel."""
  19         wx.Panel.__init__(self, parent, *args, **kwargs)
  20 
  21         self.parent = parent  # Sometimes one can use inline Comments
  22 
  23         NothingBtn = wx.Button(self, label="Do Nothing with a long label")
  24         NothingBtn.Bind(wx.EVT_BUTTON, self.DoNothing )
  25 
  26         MsgBtn = wx.Button(self, label="Send Message")
  27         MsgBtn.Bind(wx.EVT_BUTTON, self.OnMsgBtn )
  28 
  29         Sizer = wx.BoxSizer(wx.VERTICAL)
  30         Sizer.Add(NothingBtn, 0, wx.ALIGN_CENTER|wx.ALL, 5)
  31         Sizer.Add(MsgBtn, 0, wx.ALIGN_CENTER|wx.ALL, 5)
  32 
  33         self.SetSizerAndFit(Sizer)
  34 
  35     def DoNothing(self, event=None):
  36         """Do nothing."""
  37         pass
  38 
  39     def OnMsgBtn(self, event=None):
  40         """Bring up a wx.MessageDialog with a useless message."""
  41         dlg = wx.MessageDialog(self,
  42                                message='A completely useless message',
  43                                caption='A Message Box',
  44                                style=wx.OK|wx.ICON_INFORMATION
  45                                )
  46         dlg.ShowModal()
  47         dlg.Destroy()
  48 
  49 class DemoFrame(wx.Frame):
  50     """Main Frame holding the Panel."""
  51     def __init__(self, *args, **kwargs):
  52         """Create the DemoFrame."""
  53         wx.Frame.__init__(self, *args, **kwargs)
  54 
  55         # Build the menu bar
  56         MenuBar = wx.MenuBar()
  57 
  58         FileMenu = wx.Menu()
  59 
  60         item = FileMenu.Append(wx.ID_EXIT, text="&Quit")
  61         self.Bind(wx.EVT_MENU, self.OnQuit, item)
  62 
  63         MenuBar.Append(FileMenu, "&File")
  64         self.SetMenuBar(MenuBar)
  65 
  66         # Add the Widget Panel
  67         self.Panel = DemoPanel(self)
  68 
  69         self.Fit()
  70 
  71     def OnQuit(self, event=None):
  72         """Exit application."""
  73         self.Close()
  74 
  75 if __name__ == '__main__':
  76     app = wx.App()
  77     frame = DemoFrame(None, title="Micro App")
  78     frame.Show()
  79     app.MainLoop()

Comments

Put your comments here.

Please also feel free to add to this page, though if you want to change something, please discuss on the wxPython-users group first (unless you're RobinDunn).


For good python coding style in general:

Also note that wxPython uses getter and setter methods (e.g. GetLabel(), SetLabel(str)) because it is a wrapper for another language. For native python modules you should use @property instead. Look at this stack over-flow question: properties and the Python docs: property. Of course, if you are writing a custom or extended wxPython class, use the wx style for consistency.

-- AnthonyGlaser 2013-05-11 16:15:53


History

First Written 1/11/2006 by Chris Barker, with a lot of help from the wxPython-users mailing list.

Franz Steinhaeusler, 16. Jan. 2006:

14/1/2010 - Added StdDialogButtonSizer

wxPython Style Guide (last edited 2013-07-11 17:06:16 by rockford1)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.