Skip to content

PyBCWxPython

Katy Huff edited this page Jan 24, 2012 · 4 revisions

TOC(PyBc, PyBc/Session01, PyBc/Session02, PyBc/Session03, PyBc/Session04, PyBc/Session05, PyBc/Session06, PyBc/Session07, PyBc/Session08, PyBc/Session09, PyBc/f2py, PyBc/swig, PyBc/Cpython, PyBc/Cython, PyBc/PyTables, PyBc/PyTaps, PyBc/PythonBots, PyBc/Django, PyBc/GIS, PyBc/AdvancedPython, PyBc/WxPython, PyBc/standardlib, depth=1)

= Making GUI's with !WxPython =

At some point, you are probably going to want to make graphical applications in python. I'm going to give a short introduction to my favorite package for making GUIs - [http://www.wxpython.org wxPython]. !WxPython is a wrapper around another popular GUI library called wxWidgets that was written for the C++ programming language. By moving your GUI development to python, a lot of the tedium of writing C++ based GUI's can be eliminated. There are many, many graphical toolkits available, such as GTK, QT, etc...so why choose wxPython? Well, I like it because it is widely used and platform independent. So in theory, you can write applications that work on Windows, Mac, and Linux without too much difficulty. It is also full featured, has good documentation, and is relatively easy to learn. There are a lot of ins and outs to writing wxPython applications and GUI's in general which we obviously don't have time to explore. So I thought I could just show you two simple examples, then tell where you can learn more. Be aware that if you're new to object oriented programming and GUI development, then the code you see here may seem a little strange to you.

== Installation Information ==

If you are on Windows or Mac and installed the Enthought python distribution, then you are in luck because wxpython is already installed. On Ubuntu Linux (version greater than 9.04, Jaunty), installing wxpython is a breeze, simply enter the following command into the terminal:

{{{ sudo apt-get install python-wxgtk2.8 wx2.8-examples }}}

To test your installation, open ipython and type "import wx". If nothing happens, then you are all set.

== The Simplest Example ==

Lets write a script which contains the simplest imaginable wxPython example. As you may have deduced, all wxPython code can be accessed through the module wx, so all of our scripts should start with "import wx".

{{{ #!CodeExample #!python import wx

class App(wx.App):
def OnInit(self):
# This method gets called when the application starts up. frame = wx.Frame(parent=None, title='Window Title') frame.Show() return True

app = App() app.MainLoop() }}}

If you run this this script, you should see an empty frame pop up. Ordinarily you would call what popped up a window, but the word window has a special meaning in Wx. A window is anything that you see in a GUI application. For example, lets say our simple application had a button. That button is a type of window in the Wx terminology. A check box is a different type of window. I know this is a little confusing, but this is the terminology chosen by the wx developers, so you may see it pop up. What you normally call a window is called a frame in wx. Hence, this application simply creates a single frame.

== A more substantial example ==

Below I've shown a meatier example. If you run this script, you'll see that a frame pops up that has two text boxes on it, one labeled "Size" and the other labeled "Pos". The size text box has two numbers on it that represent the size of the frame, in pixels. The size text box has two numbers in it that measure the position of the frame, in pixels, relative to the top left corner of your screen. As you move the frame around or change its size, you'll see that the numbers in the text boxes change accordingly.

{{{ #!CodeExample #!python #!/usr/bin/env python #---------------------------------------------------------------------------- # Name: test7.py # Purpose: A minimal wxPython test program # # Author: Robin Dunn # # Created: A long time ago, in a galaxy far, far away... # Copyright: (c) 1998 by Total Control Software # Licence: wxWidgets license #----------------------------------------------------------------------------

# NOTE: this sample requires wxPython 2.6 or newer

# import the wxPython GUI package import wx

# Create a new frame class, derived from the wxPython Frame. class MyFrame(wx.Frame):

def __init__(self, parent, title):

# First, call the base class' __init__ method to create the frame wx.Frame.__init__(self, parent=parent, title=title)

# Add a panel and some controls to display the size and position panel = wx.Panel(parent=self) label1 = wx.StaticText(parent=panel, label="Size:") label2 = wx.StaticText(parent=panel, label="Pos:") self.sizeCtrl = wx.TextCtrl(parent=panel, value="", style=wx.TE_READONLY) self.posCtrl = wx.TextCtrl(parent=panel, value="", style=wx.TE_READONLY) self.panel = panel

# Use some sizers for layout of the widgets sizer = wx.FlexGridSizer(2, 2) sizer.Add(label1) sizer.Add(self.sizeCtrl) sizer.Add(label2) sizer.Add(self.posCtrl)

border = wx.BoxSizer() border.Add(sizer, 0, wx.ALL, 15) panel.SetSizerAndFit(border) self.Fit()

# Associate some events with methods of this class self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_MOVE, self.OnMove)

# This method is called by the System when the window is resized, # because of the association above. def OnSize(self, event):

size = event.GetSize() self.sizeCtrl.SetValue("%s, %s" % (size.width, size.height))

# tell the event system to continue looking for an event handler, # so the default handler will get called. event.Skip()

# This method is called by the System when the window is moved, # because of the association above. def OnMove(self, event):

pos = event.GetPosition() self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y))

# Every wxWidgets application must have a class derived from wx.App class MyApp(wx.App):

# wxWindows calls this method to initialize the application def OnInit(self):

# Create an instance of our customized Frame class frame = MyFrame(None, "This is a test") frame.Show(True)

# Tell wxWindows that this is our main window self.SetTopWindow(frame)

# Return a success flag return True

app = MyApp(0) # Create an instance of the application class app.MainLoop() # Tell it to start processing events }}}

== Basic components of !WxPython ==

Sizers, Controls, Events

There are a few basic components of wxPython. We saw a few of them in the previous example:

  • '''Controls:''' Controls are things like buttons, text boxes, check boxes, etc... We place controls in our frames to communicate information to the user and to allow them to do things.
  • '''Sizers:''' These tell wxPython how to lay out the all of the controls, and what to do if the window size changes.
  • '''Events:''' Events are things that happen. For example, if the user moves the mouse - that is an event. If the user presses a button - that is another event. We can ''bind'' events to functions using the wx.Bind function. For example, lets say that when the user clicks the mouse, we want to print the position of the mouse. We would first write a function that printed the position of the mouse. Then we would use wx.Bind to tell wxPython to call our function when the left mouse button was clicked (i.e. when the wx.EVT_LEFT_DOWN event was encountered)

== Where to go from here ==

There are a few key sources of wxPython information which I have listed below:

  • If you are serious about writing GUI's in python with wxPython then I strongly recommend that you get the book "wxPython in Action" by Noel Rappin and Robin Dunn. It is a great introduction to wxPython and doesn't assume that you have any GUI writing experience. So if you are just starting, it is a great resource. Even if you are familiar with writing GUI's in other languages I would still recommend it.
  • The wxPython web site, [http://www.wxpython.org], is also a great resource/reference. From there you'll find links to other important resources
  • Finally, and most importantly, the demo script that comes with wxPtyhon is essential. Usually, your work flow is going to begin with having an application in mind that has a certain behavior. For example, maybe you decide you need an application that has a tree like, hierarchical control that allows you to collapse each node. Now you have to figure out how to do this in !WxPython. This is what the demo is for. It is a !WxPython application that showcases almost every feature of the library and provides you the code to use the feature yourself. You can acquire it from the wxPython web site. The book is a really good resource when you are getting started with wxPython, but once you are fairly fluent, the demo script will become absolutely indispensable.
'''Hands On Example:'''
  • Change the text "Pos:" on the frame to "Position:"
  • Create two new static text controls. Call them st1 and st2. Label st1 using the text "col1" and st2 using the text "col2"
  • Add st1 to the frame above the text that says "Size:". Add st2 above the text box that contains the size information for the frame. When you are done, your frame should look like:

Image(Screenshot.png)

Clone this wiki locally