Wxpython Tutorial PDF
Wxpython Tutorial PDF
Audience
This tutorial is designed for software programmers who are keen on learning how to
develop GUI applications for the desktop.
Prerequisites
You should have a basic understanding of computer programming terminologies. A basic
understanding of Python and any of the programming languages is a plus.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected].
i
wxPython
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
1. WXPYTHON – INTRODUCTION............................................................................................. 1
Windows ................................................................................................................................................. 2
Linux ....................................................................................................................................................... 2
MacOS..................................................................................................................................................... 2
ii
wxPython
MessageDialog ...................................................................................................................................... 77
wx.TextEntryDialog ............................................................................................................................... 79
iii
wxPython
iv
1. wxPython – Introduction wxPython
wxPython is a Python wrapper for wxWidgets (which is written in C++), a popular cross-
platform GUI toolkit. Developed by Robin Dunn along with Harri Pasanen, wxPython is
implemented as a Python extension module.
Just like wxWidgets, wxPython is also a free software. It can be downloaded from the official
website http://wxpython.org. Binaries and source code for many operating system platforms
are available for download on this site.
Principal modules in wxPython API include a core module. It consists of wxObject class,
which is the base for all classes in the API. Control module contains all the widgets used in
GUI application development. For example, wx.Button, wx.StaticText (analogous to a label),
wx.TextCtrl (editable text control), etc.
wxPython API has GDI (Graphics Device Interface) module. It is a set of classes used for
drawing on widgets. Classes like font, color, brush, etc. are a part of it. All the container
window classes are defined in Windows module.
Official website of wxPython also hosts Project Phoenix – a new implementation of wxPython
for Python 3.*. It focuses on improving speed, maintainability, and extensibility. The project
began in 2012 and is still in beta stage.
5
2. wxPython –Environment wxPython
Windows
Prebuilt binaries for Windows OS (both 32 bit and 64 bit) are available on
http://www.wxpython.org/download.php page. Latest versions of installers available are:
wxPython demo, samples and wxWidgets documentation is also available for download on the
same page.
wxPython3.0-win32-docs-demos.exe
Linux
wxPython binaries for many Linux distros can be found in their respective repositories.
Corresponding package managers will have to be used to download and install. For instance
on Debian Linux, following command should be able to install wxPython.
MacOS
Prebuilt binaries for MacOS in the form of disk images are available on the download page of
the official website.
6
3. wxPython – Hello World wxPython
A simple GUI application displaying Hello World message is built using the following steps:
Import wx module.
Create a top level window as object of wx.Frame class. Caption and size parameters
are given in constructor.
Although other controls can be added in Frame object, their layout cannot be managed.
Hence, put a Panel object into the Frame.
Add a StaticText object to display ‘Hello World’ at a desired position inside the window.
import wx
app = wx.App()
window = wx.Frame(None,title="wxPython Frame",size=(300,200))
panel=wx.Panel(window)
label=wx.StaticText(panel,label="Hello World",pos=(100,50))
window.Show(True)
app.MainLoop()
7
wxPython
wxFrame object is the most commonly employed top level window. It is derived from
wxWindow class. A frame is a window whose size and position can be changed by the user.
It has a title bar and control buttons. If required, other components like menu bar, toolbar
and status bar can be enabled. A wxFrame window can contain any frame that is not a dialog
or another frame.
8
4. wxPython – Frame Class wxPython
wx.Frame Class has a default constructor with no arguments. It also has an overloaded
constructor with the following parameters:
Parameter Description
wx.CAPTION
wx.MINIMIZE_BOX
wx.MAXIMIZE_BOX
wx.CLOSE_BOX
wx.SYSTEM_MENU
wx.RESIZE_BORDER
9
wxPython
wx.STAY_ON_TOP
wx.FRAME_FLOAT_ON_PARENT
Example
window=wx.Frame(None, -1, “Hello”, pos=(10,10), size=(300,200), style=
wxDEFAULT_FRAME_STYLE, name=”frame”)
10
wxPython
11
5. wxPython – Panel Class wxPython
Widgets such as button, text box, etc. are placed on a panel window. wx.Panel class is
usually put inside a wxFrame object. This class is also inherited from wxWindow class.
Although controls can be manually placed on panel by specifying the position in screen
coordinates, it is recommended to use a suitable layout scheme, called sizer in wxPython, to
have better control over the placement and address the resizing issue.
In wxPanel constructor, the parent parameter is the wx.Frame object in which the panel is
to be placed. Default value of id parameter is wx.ID_ANY, whereas the default style parameter
is wxTAB_TRAVERSAL.
wxPython API has the following sizers, using which controls are added into a panel object:
wx.FlexGridSizer Control added in cell grid can occupy more than one cell
Sizer object is applied as the layout manager of the panel using SetSizer() method of wxPanel
class.
wx.Panel.SetSizer(wx.???Sizer())
12
6. wxPython – GUI Builder Tools wxPython
Creating a good looking GUI by manual coding can be tedious. A visual GUI designer tool is
always handy. Many GUI development IDEs targeted at wxPython are available. Following are
some of them:
wxFormBuilder
wxDesigner
wxGlade
BoaConstructor
gui2py
wxFormBuilder is an open source, cross-platform WYSIWYG GUI builder that can translate
the wxWidget GUI design into C++, Python, PHP or XML format. A brief introduction to usage
of wxFormBuilder is given here.
First of all the latest version of wxFormBuilder needs to be downloaded and installed from
http://sourceforge.net/projects/wxformbuilder/. On opening the application, a new project
with blank grey area at the center appears.
Give a suitable name to the project and choose Python as code generation language. This is
done in the Object properties window as shown in the following image:
13
wxPython
Add necessary controls in the Box with suitable captions. Here, a StaticText (label), two
TextCtrl objects (text boxes) and a wxButton object are added. The frame looks like the
following image:
Enable Expand and Stretch on these three controls. In the object properties for wxButton
object, assign a function findsquare() to OnButtonClick event.
15
wxPython
Save the project and press F8 to generate Python code for developed GUI. Let the generated
file be named as Demo.py
In the executable Python script, import demo.py and define FindSquare() function. Declare
Application object and start a main event loop. Following is the executable code:
import wx
class CalcFrame(demo.MyFrame1):
def __init__(self,parent):
demo.MyFrame1.__init__(self,parent)
def FindSquare(self,event):
num = int(self.m_textCtrl1.GetValue())
self.m_textCtrl2.SetValue (str(num*num))
app = wx.App(False)
frame = CalcFrame(None)
frame.Show(True)
16
wxPython
17
7. wxPython – Major Classes wxPython
Original wxWidgets (written in C++) is a huge class library. GUI classes from this library are
ported to Python with wxPython module, which tries to mirror the original wxWidgets library
as close as possible. So, wx.Frame class in wxPython acts much in the same way as wxFrame
class in its C++ version.
wxObject is the base for most of the classes. An object of wxApp (wx.App in wxPython)
represents the application itself. After generating the GUI, application enters in an event loop
by MainLoop() method. Following diagrams depict the class hierarchy of most commonly used
GUI classes included in wxPython.
18
wxPython
19
wxPython
20
wxPython
21
8. wxPython – Event Handling wxPython
Unlike a console mode application, which is executed in a sequential manner, a GUI based
application is event driven. Functions or methods are executed in response to user’s actions
like clicking a button, selecting an item from collection or mouse click, etc., called events.
Data pertaining to an event which takes place during the application’s runtime is stored as
object of a subclass derived from wx.Event. A display control (such as Button) is the source
of event of a particular type and produces an object of Event class associated to it. For
instance, click of a button emits a wx.CommandEvent. This event data is dispatched to event
handler method in the program. wxPython has many predefined event binders. An Event
binder encapsulates relationship between a specific widget (control), its associated event
type and the event handler method.
For example, to call OnClick() method of the program on a button’s click event, the following
statement is required:
self.b1.Bind(EVT_BUTTON, OnClick)
Bind() method is inherited by all display objects from wx.EvtHandler class. EVT_.BUTTON
here is the binder, which associates button click event to OnClick() method.
Example
In the following example, the MoveEvent, caused by dragging the top level window – a
wx.Frame object in this case – is connected to OnMove() method using wx.EVT_MOVE
binder. The code displays a window. If it is moved using mouse, its instantaneous coordinates
are displayed on the console.
import wx
class Example(wx.Frame):
def InitUI(self):
self.Bind(wx.EVT_MOVE, self.OnMove)
self.SetSize((250, 180))
22
wxPython
self.SetTitle('Move event')
self.Centre()
self.Show(True)
ex = wx.App()
Example(None)
ex.MainLoop()
23
wxPython
Some of the subclasses inherited from wx.Event are listed in the following table:
Events in wxPython are of two types. Basic events and Command events. A basic event stays
local to the window in which it originates. Most of the wxWidgets generate command events.
A command event can be propagated to window or windows, which are above the source
window in class hierarchy.
Example
Following is a simple example of event propagation. The complete code is:
import wx
class MyPanel(wx.Panel):
24
wxPython
def btnclk(self,e):
print "Button received click event. propagated to Panel class"
e.Skip()
class Example(wx.Frame):
def __init__(self,parent):
super(Example, self).__init__(parent)
self.InitUI()
def InitUI(self):
mpnl = MyPanel(self)
self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)
ex = wx.App()
25
wxPython
Example(None)
ex.MainLoop()
In the above code, there are two classes. MyPanel, a wx.Panel subclass and Example, a
wx.Frame subclass which is the top level window for the program. A button is placed in the
panel.
This Button object is bound to an event handler btnclk() which propagates it to parent class
(MyPanel in this case). Button click generates a CommandEvent which can be propagated
to its parent by Skip() method.
MyPanel class object also binds the received event to another handler OnButtonClicked(). This
function in turn transmits to its parent, the Example class. The above code produces the
following output:
26
wxPython
27