= The wxPython Linux tutorial =
'''Table of Contents:'''

<<TableOfContents>>

== Foreword ==
The purpose of this tutorial is to get you started with the wxPython toolkit, from the basics to the advanced topics.

It has lots of code examples, not much talking. After that, you will be able to dig in yourself.

 * mailing list
 * reference book
 * source code of wxPython applications
 * /home/vronskij/bin/wxPython/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx - the ultimate resource, on my Linux box

There are three decent toolkits for the python programming language :

 * {{{wxPython}}}
 * {{{PyQt}}}
 * {{{PyGTK}}}

Note that this tutorial is done on '''Linux '''but the scripts work correctly on '''Windows :'''

- '''Tested''''' py3.x, wx4.x and Win10).''

Icons and images :

- Icons used in this tutorial: [[attachment:icons.tgz]]

- Images used in this tutorial: [[attachment:images.tgz]]

Jan Bodnar 2005 - 2007.

Status update. (april 2007).

All my work on wxPython tutorial has been moved to my website :

http://www.zetcode.com/wxpython

https://github.com/janbodnar/wxPython-examples

Here I shall not add any more examples. If I find myself some time, I will do some polishing.

== wxPython API ==
wxPython API is a set of functions and widgets. Widgets are essential building blocks of a GUI application. Under Windows widgets are calles controls. We can roughly divide programmers into two groups. They code applications or libraries. In our case, wxPython is  a library that is used by application programmers to code applications. Technically, wxPython is a wrapper over a C++ GUI API called wxWidgets. So it is not a native API. e.g. not written  directly in Python. The only native GUI library for an interpreted language that I know is Java's Swing library.

In wxPython we have lot's of widgets. These can be divided into some logical groups.

'''Base Widgets'''

These widgets provide basic functionality for derived widgets. They are usually not used directly.

 * {{{wx.Window}}}
 * {{{wx.Control}}}
 * {{{wx.ControlWithItem}}}

'''Top level Widgets'''

These widgets exist independently of each other.

 * {{{wx.Frame}}}
 * {{{wx.MDIParentFrame}}}
 * {{{wx.MDIChildFrame}}}
 * {{{wx.Dialog}}}
 * {{{wx.PopupWindow}}}

'''Containers'''

Containers contain other widgets. These widgets are called children.

 * {{{wx.Panel}}}
 * {{{wx.Notebook}}}
 * {{{wx.ScrolledWindow}}}
 * {{{wx.SplitterWindow}}}

'''Dynamic Widgets'''

These widgets can be edited by users.

 * {{{wx.Button}}}
 * {{{wx.BitmapButton}}}
 * {{{wx.Choice}}}
 * {{{wx.ComboBox}}}
 * {{{wx.CheckBox}}}
 * {{{wx.Grid}}}
 * {{{wx.ListBox}}}
 * {{{wx.RadioBox}}}
 * {{{wx.RadioButton}}}
 * {{{wx.ScrollBar}}}
 * {{{wx.SpinButton}}}
 * {{{wx.SpinCtrl}}}
 * {{{wx.Slider}}}
 * {{{wx.TextCtrl}}}
 * {{{wx.ToggleButton}}}

'''Static Widgets'''

These widgets display informatin. They cannot be edited by user.

 * {{{wx.Gauge}}}
 * {{{wx.StaticText}}}
 * {{{wx.StaticBitmap}}}
 * {{{wx.StaticLine}}}
 * {{{wx.StaticBox}}}

'''Other Widgets'''

These widgets implement statusbar, toolbar and menubar in an application.

 * {{{wx.MenuBar}}}
 * {{{wx.ToolBar}}}
 * {{{wx.StatusBar}}}

== First Steps ==
We start with a simple example.

{{{#!python
#!/usr/bin/python

# simple.py

import wx

#---------------------------------------------------------------------------

app = wx.App()

frame = wx.Frame(None, -1, 'Simple.py')
frame.Show()

app.MainLoop()
}}}
In every wxPython application, we must import the wx library.

{{{
import wx
}}}
An application object is created by initiating class {{{wx.App}}}.

{{{
app = wx.App()
}}}
We create a frame widget. The window pops up only if we call Show() method on a widget.

{{{
frame = wx.Frame(None, -1, "simple.py")
frame.Show()
}}}
The last line enters a Mainloop. A mainloop is an endless cycle that catches up all events coming up to your application. It is an integral part of any windows GUI application.

{{{
app.MainLoop()
}}}
Although the code is very simple, you can do a lot of things with your window. You can maximize it, minimize it, move it, resize it. All these things have been already done.

{{attachment:simple.png}}

'''Figure: simple.py'''

=== wx.Window ===
wx.Window is a base class out of which many widgets inherit. For instance, the wx.Frame widget inherits from wx.Window. Technically it means that we can use wx.Window's methods for all descendants. We will introduce here some of its methods.

 * {{{SetTitle(string title)}}} - Sets the window's title. Applicable only to frames and dialogs.
 * {{{SetToolTip(wx.ToolTip tip)}}} - Attaches a tooltip to the window.
 * {{{SetSize(wx.Size size)}}} - Sets the size of the window.
 * {{{SetPosition(wx.Point pos)}}} - Positions the window to given coordinates
 * {{{Show(show=True)}}} - Shows or hides the window. show parameter can be True or False.
 * {{{Move(wx.Point pos)}}} - Moves the window to the given position.
 * {{{SetCursor(wx.StockCursor id)}}} - Sets the window's cursor.

{{{#!python
#!/usr/bin/python

# simple2.py

import wx

#---------------------------------------------------------------------------

app = wx.App()

frame = wx.Frame(None, -1, '')
frame.SetToolTip(wx.ToolTip('This is a frame'))
frame.SetCursor(wx.Cursor(wx.CURSOR_MAGNIFIER))
frame.SetPosition(wx.Point(0,0))
frame.SetSize(wx.Size(300,250))
frame.SetTitle('Simple2.py')
frame.Show()

app.MainLoop()
}}}
We create a 'This is a frame' tooltip. The cursor is set to a magnifier cursor. Possible cursor id's: [[#head-ba098791be2c102e4c44bd330ce13c25a78764d2|are listed below]] We position the window to the upper left corner and size it to 300x250 pixels. Title is set to 'simple2.py'.

=== wx.Frame ===
Link :

[[https://wiki.wxpython.org/How%20to%20create%20a%20frame%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20frame%20%28Phoenix%29]]

{{attachment:icon.png}}

'''Figure: icon.py'''

=== wx.MenuBar ===
To set up a menubar in your wxPython application is pretty simple. We will discuss adding menus to menubar, adding submenus to existing menus. Each menu consists of menuitems. Menuitems can be normal items, check items or radio items.

First thing  to do is to create a menubar.

{{{
menubar = wx.MenuBar()
}}}
Then we create our menus.

{{{
file = wx.Menu()
edit = wx.Menu()
help = wx.Menu()
}}}
Then we add some items into the menu. This can be done in two ways.

{{{
file.Append(101, '&Open', 'Open a new document')
file.Append(102, '&Save', 'Save the document')
}}}
We can separate logical sections in menus with a horizontal line.

{{{
file.AppendSeparator()
}}}
If you want to have some icons in your menus, you need to create {{{MenuItem}}} objects manually.

{{{
quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
quit.SetBitmap(wx.Image('stock_exit-16.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())
file.Append(quit)
}}}
wxPython toolkit can only put bitmaps into menus. Therefore we need to convert our PNG files into bitmaps.

Menus are then added into the menubar.

{{{
menubar.Append(file, '&File')
menubar.Append(edit, '&Edit')
menubar.Append(help, '&Help')
}}}
Finally we set up our menubar in our application class.

{{{
self.SetMenuBar(menubar)
}}}
Let's sum it up in a small script.

{{{#!python
#!/usr/bin/python

# menu1.py

import wx

#---------------------------------------------------------------------------

class MyMenu(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(300, 200))

        menubar = wx.MenuBar()

        file = wx.Menu()
        edit = wx.Menu()
        help = wx.Menu()

        file.Append(101, '&Open', 'Open a new document')
        file.Append(102, '&Save', 'Save the document')
        file.AppendSeparator()
        quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
        quit.SetBitmap(wx.Image('stock_exit-16.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        file.Append(quit)

        menubar.Append(file, '&File')
        menubar.Append(edit, '&Edit')
        menubar.Append(help, '&Help')

        self.SetMenuBar(menubar)

        #------------

        self.Bind(wx.EVT_MENU, self.OnQuit, id=105)

        #------------

        self.CreateStatusBar()

    #-----------------------------------------------------------------------

    def OnQuit(self, event):
        self.Close()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyMenu(None, -1, 'Menu1.py')
        frame.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
So far we have seen the default, normal menu items. Here we see, how we can explicitly define check items, normal items or radio items.

{{{
edit.Append(201, 'check item1', '', wx.ITEM_CHECK)
edit.Append(202, 'check item2', '', kind=wx.ITEM_CHECK)
}}}
or

{{{
quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application', wx.ITEM_NORMAL)
}}}
The parameter is called kind.

Possible {{{wx.ItemKind}}}-s

 * wx.ITEM_NORMAL - default item
 * wx.ITEM_CHECK - check item
 * wx.ITEM_RADIO - radio item

If you want to create a submenu, you create a menu first.

{{{
submenu = wx.Menu()
}}}
Then append some menu items into this submenu.

{{{
submenu.Append(301, 'radio item1', kind=wx.ITEM_RADIO)
submenu.Append(302, 'radio item2', kind=wx.ITEM_RADIO)
submenu.Append(302, 'radio item3', kind=wx.ITEM_RADIO)
}}}
You finish with adding a submenu into a menu object.

{{{
edit.Append(203, 'submenu', submenu)
}}}
We now discuss how to respond to user actions. We will touch on it only briefly and explain it later in more detail.

So when a user of our application selects a menu item, an event is generated. We must provide an event handler, that will react to this event accordingly. Handling events in wxPython is the most elegant and simple that I have seen so far. When we look into the reference book, we find wx.EVT_MENU handler under Event handling section.

Suppose we want to add an event handler to our quit menu item.

{{{
self.Bind(wx.EVT_MENU, self.OnQuit, id=105)
}}}
We need to provide three pieces of information. The object, where we bind our event handler. In our case self, the application's main object. The id of the corresponding menu item. And the method name, which will do our job.

The method which will react to user actions has two parameters. The first one is the object where this method is defined. The second one is the generated event. This time, we do without it. We simply close our application.

{{{
def OnQuit(self, event):
    self.Close()
}}}
The following script demonstrates various menu items, submenu and one simple event handler. I hate when my application window pops up somewhere in the corner by the will of the allmighty window manager. So I added

{{{
self.Centre()
}}}
so that the window pops up in the center of the screen.

{{attachment:menu1.png}}

'''Figure: menu1.py'''

{{{#!python
#!/usr/bin/python

# menu2.py

import wx

#---------------------------------------------------------------------------

class MyMenu(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(380, 250))

        menubar = wx.MenuBar()

        file = wx.Menu()
        edit = wx.Menu()
        help = wx.Menu()

        file.Append(101, '&Open', 'Open a new document')
        file.Append(102, '&Save', 'Save the document')
        file.AppendSeparator()
        quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
        quit.SetBitmap(wx.Image('stock_exit-16.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        file.Append(quit)

        edit.Append(201, 'check item1', '', wx.ITEM_CHECK)
        edit.Append(202, 'check item2', kind=wx.ITEM_CHECK)
        submenu = wx.Menu()
        submenu.Append(301, 'radio item1', kind=wx.ITEM_RADIO)
        submenu.Append(302, 'radio item2', kind=wx.ITEM_RADIO)
        submenu.Append(303, 'radio item3', kind=wx.ITEM_RADIO)
        edit.Append(203, 'submenu', submenu)

        menubar.Append(file, '&File')
        menubar.Append(edit, '&Edit')
        menubar.Append(help, '&Help')

        self.SetMenuBar(menubar)

        #------------

        self.Bind(wx.EVT_MENU, self.OnQuit, id=105)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnQuit(self, event):
        self.Close()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyMenu(None, -1, 'Menu2.py')
        frame.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{attachment:menu2.png}}

'''Figure: menu2.py'''

=== wx.ToolBar ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20tool%20bar%20%28Phoenix%29

{{attachment:toolbar.png}}

'''Figure: toolbar.py'''

== Layout  Management ==
There are basically two methods for layout of our widgets. The first method is manual. We place widgets by specifying the position in the constructor of the widget.

{{{#!python
#!/usr/bin/python

# layout.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(300, 100))

        panel = wx.Panel(self, -1)

        wx.Button(panel, -1, "Button1", (0, 0))
        wx.Button(panel, -1, "Button2", (80, 0))
        wx.Button(panel, -1, "Button3", (160, 0))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Layout.py')
        frame.Show(True)
        frame.Centre()

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
When the window is resized, the size and the position of buttons do not change. This is one of the main features of the manual positioning of the widgets.

{{attachment:layout.png}}

'''Figure: layout.py'''

The second method is to use layout managers. This method is prevalent in real programs. Basically you use sizers. We will discuss

 * {{{wx.BoxSizer}}}
 * {{{wx.StaticBoxSizer}}}
 * {{{wx.GridSizer}}}
 * {{{wx.GridBagSizer}}}

=== wx.BoxSizer ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20box%20sizer%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20box%20sizer%20%28Phoenix%29]]

{{attachment:wxboxsizer.png}}

'''Figure: wxboxsizer.py'''

=== Borders ===
We show four various border styles available in wxPython. Border is a simple window decoration.

Available Borders:

 * wx.SIMPLE_BORDER
 * wx.RAISED_BORDER
 * wx.SUNKEN_BORDER
 * wx.NO_BORDER

{{{#!python
#!/usr/bin/python

# borders.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        pnl1 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        pnl2 = wx.Panel(self, -1, style=wx.RAISED_BORDER)
        pnl3 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
        pnl4 = wx.Panel(self, -1, style=wx.NO_BORDER)

        #------------

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        hbox.Add(pnl1, 1, wx.EXPAND | wx.ALL, 3)
        hbox.Add(pnl2, 1, wx.EXPAND | wx.ALL, 3)
        hbox.Add(pnl3, 1, wx.EXPAND | wx.ALL, 3)
        hbox.Add(pnl4, 1, wx.EXPAND | wx.ALL, 3)

        self.SetSize((400, 120))
        self.SetSizer(hbox)

        #------------

        self.Centre()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Borders.py')
        frame.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}

{{attachment:borders.png}}

'''Figure: borders.py'''

=== wx.GridSizer ===
{{{wx.GridSizer}}} lays out its children in a two-dimensional table. The width of each field is the width of the widest child. The height of each field is the height of the tallest child.

{{{
wx.GridSizer(integer rows, integer cols, integer vgap, integer hgap)
}}}
In the constructor we provide the number of rows and  the number of columns of our table and the horizontal and vertical gap between the children widgets. We insert our widgets into the table with the {{{AddMany()}}} method. Children are inserted from left to right, top to bottom.

{{{#!python
#!/usr/bin/python

# calculator.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(300, 250))

        self.formula = False

        #------------

        menubar = wx.MenuBar()
        file = wx.Menu()
        file.Append(22, '&Quit', 'Exit Calculator')
        menubar.Append(file, '&File')
        self.SetMenuBar(menubar)

        #------------

        self.display = wx.TextCtrl(self, -1, '',  style=wx.TE_RIGHT)

        #------------

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.display, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 4)

        gs = wx.GridSizer(5, 4, 3, 3)
        gs.AddMany([(wx.Button(self, 20, 'Cls'), 0, wx.EXPAND),
                    (wx.Button(self, 21, 'Bck'), 0, wx.EXPAND),
                    (wx.StaticText(self, -1, ''), 0, wx.EXPAND),
                    (wx.Button(self, 22, 'Close'), 0, wx.EXPAND),
                    (wx.Button(self, 1, '7'), 0, wx.EXPAND),
                    (wx.Button(self, 2, '8'), 0, wx.EXPAND),
                    (wx.Button(self, 3, '9'), 0, wx.EXPAND),
                    (wx.Button(self, 4, '/'), 0, wx.EXPAND),
                    (wx.Button(self, 5, '4'), 0, wx.EXPAND),
                    (wx.Button(self, 6, '5'), 0, wx.EXPAND),
                    (wx.Button(self, 7, '6'), 0, wx.EXPAND),
                    (wx.Button(self, 8, '*'), 0, wx.EXPAND),
                    (wx.Button(self, 9, '1'), 0, wx.EXPAND),
                    (wx.Button(self, 10, '2'), 0, wx.EXPAND),
                    (wx.Button(self, 11, '3'), 0, wx.EXPAND),
                    (wx.Button(self, 12, '-'), 0, wx.EXPAND),
                    (wx.Button(self, 13, '0'), 0, wx.EXPAND),
                    (wx.Button(self, 14, '.'), 0, wx.EXPAND),
                    (wx.Button(self, 15, '='), 0, wx.EXPAND),
                    (wx.Button(self, 16, '+'), 0, wx.EXPAND)])

        sizer.Add(gs, 1, wx.EXPAND)
        self.SetSizer(sizer)

        #------------

        self.Bind(wx.EVT_BUTTON, self.OnClear, id=20)
        self.Bind(wx.EVT_BUTTON, self.OnBackspace, id=21)
        self.Bind(wx.EVT_BUTTON, self.OnClose, id=22)
        self.Bind(wx.EVT_BUTTON, self.OnSeven, id=1)
        self.Bind(wx.EVT_BUTTON, self.OnEight, id=2)
        self.Bind(wx.EVT_BUTTON, self.OnNine, id=3)
        self.Bind(wx.EVT_BUTTON, self.OnDivide, id=4)
        self.Bind(wx.EVT_BUTTON, self.OnFour, id=5)
        self.Bind(wx.EVT_BUTTON, self.OnFive, id=6)
        self.Bind(wx.EVT_BUTTON, self.OnSix, id=7)
        self.Bind(wx.EVT_BUTTON, self.OnMultiply, id=8)
        self.Bind(wx.EVT_BUTTON, self.OnOne, id=9)
        self.Bind(wx.EVT_BUTTON, self.OnTwo, id=10)
        self.Bind(wx.EVT_BUTTON, self.OnThree, id=11)
        self.Bind(wx.EVT_BUTTON, self.OnMinus, id=12)
        self.Bind(wx.EVT_BUTTON, self.OnZero, id=13)
        self.Bind(wx.EVT_BUTTON, self.OnDot, id=14)
        self.Bind(wx.EVT_BUTTON, self.OnEqual, id=15)
        self.Bind(wx.EVT_BUTTON, self.OnPlus, id=16)
        self.Bind(wx.EVT_MENU, self.OnClose, id=22)

        #------------

        self.SetBackgroundColour("#eceade")
        self.SetMinSize((300, 250))

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnClear(self, event):
        self.display.Clear()


    def OnBackspace(self, event):
        formula = self.display.GetValue()
        self.display.Clear()
        self.display.SetValue(formula[:-1])


    def OnClose(self, event):
        self.Close()


    def OnDivide(self, event):
        if self.formula:
            return
        self.display.AppendText('/')


    def OnMultiply(self, event):
        if self.formula:
            return
        self.display.AppendText('*')


    def OnMinus(self, event):
        if self.formula:
            return
        self.display.AppendText('-')


    def OnPlus(self, event):
        if self.formula:
            return
        self.display.AppendText('+')


    def OnDot(self, event):
        if self.formula:
            return
        self.display.AppendText('.')


    def OnEqual(self, event):
        if self.formula:
            return
        formula = self.display.GetValue()
        self.formula = False
        try:
            self.display.Clear()
            output = eval(formula)
            self.display.AppendText(str(output))
        except StandardError:
            self.display.AppendText("Error")


    def OnZero(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('0')


    def OnOne(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('1')


    def OnTwo(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('2')


    def OnThree(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('3')


    def OnFour(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('4')


    def OnFive(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('5')


    def OnSix(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('6')


    def OnSeven(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('7')


    def OnEight(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('8')


    def OnNine(self, event):
        if self.formula:
            self.display.Clear()
            self.formula = False
        self.display.AppendText('9')

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Calculator.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
The formula we input is processed by the eval built-in python function.

{{{
output = eval(formula)
}}}
If we make an error in our formula, an error message is displayed. Notice how we managed to put a space between the Bck and Close buttons. We simply put an empty {{{wx.StaticText there}}}. Such tricks are quite common.

{{attachment:calculator.png}}

'''Figure: calculator.py'''

=== wx.GridBagSizer ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20grid%20bag%20sizer%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20grid%20bag%20sizer%20%28Phoenix%29]]

== Basic Objects ==
wxPython is a collection of various objects. We can divide them into two groups.

 * Visual objects
 * Non-visual objects

Examples of visual objects are: widgets, fonts, colours or cursors. Non-visual objects: sizers, timers or events.

=== Cursors ===
A cursor is a simple graphical object. It is used to indicate position on the monitor or any other display device. It usually dynamically changes itself. Typically, when you hover a mouse pointer over a hypertext, the cursor changes to a hand.

In the next code example, we create a grid of nine {{{wx.Panels}}}. Each panel shows a different cursor.

{{{#!python
#!/usr/bin/python

# cursors.py

import wx

#---------------------------------------------------------------------------

class Cursors(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        cursors = [wx.CURSOR_ARROW, wx.CURSOR_HAND, wx.CURSOR_WATCH,
                   wx.CURSOR_SPRAYCAN, wx.CURSOR_PENCIL, wx.CURSOR_CROSS,
                   wx.CURSOR_QUESTION_ARROW, wx.CURSOR_POINT_LEFT,
                   wx.CURSOR_SIZING]

        #------------

        vbox = wx.BoxSizer(wx.VERTICAL)
        sizer = wx.GridSizer(3, 3, 2, 2)

        for i in cursors:
            panel = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
            panel.SetCursor(wx.Cursor(i))
            sizer.Add(panel, flag=wx.EXPAND)

        vbox.Add(sizer, 1, wx.EXPAND | wx.TOP, 5)
        self.SetSizer(vbox)

        #------------

        self.Centre()

        #------------

        self.Show(True)

#---------------------------------------------------------------------------

app = wx.App(0)
Cursors(None, -1, 'Cursors.py')
app.MainLoop()
}}}
Various predefined cursors: [[#head-26c168844e79da5329d8463baa7511fff18a6c5c|Listed below.]]

=== Fonts ===
We create different kinds of fonts with the wx.Font object. It has the following constructor:

{{{
wx.Font(integer pointSize, wx.FontFamily family, integer style, integer weight,
        bool underline = false, string faceName = '',
        wx.FontEncoding encoding = wx.FONTENCODING_DEFAULT)
}}}
The specified parameters can have the following options:

Family:

 * wx.DEFAULT
 * wx.DECORATIVE
 * wx.ROMAN
 * wx.SWISS
 * wx.SCRIPT
 * wx.MODERN

Style:

 * wx.NORMAL
 * wx.SLANT
 * wx.ITALIC

Weight:

 * wx.NORMAL
 * wx.LIGHT
 * wx.BOLD

fonts.py script shows three different fonts.

{{{#!python
#!/usr/bin/python

# fonts.py

import wx

#---------------------------------------------------------------------------

text1 = "Now listen to me mama\nMama mama\nYou're taking away my last chance\nDon't take it away"

text2 = '''You won't cry for my absence, I know -
You forgot me long ago.
Am I that unimportant...?
Am I so insignificant...?
Isn't something missing?
Isn't someone missing me?'''

text3 = '''But if I had one wish fulfilled tonight
I'd ask for the sun to never rise
If God passed a mic to me to speak
I'd say stay in bed, world
Sleep in peace'''

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(350, 360))

        panel = wx.Panel(self, -1)

        font1 = wx.Font(10, wx.SWISS, wx.ITALIC, wx.NORMAL)
        font2 = wx.Font(10, wx.ROMAN, wx.NORMAL, wx.NORMAL)
        font3 = wx.Font(10, wx.MODERN, wx.NORMAL, wx.BOLD)

        lyrics1 = wx.StaticText(panel, -1, text1,(70, 15), style=wx.ALIGN_CENTRE)
        lyrics1.SetFont(font1)

        lyrics2 = wx.StaticText(panel, -1, text2,(70, 100), style=wx.ALIGN_CENTRE)
        lyrics2.SetFont(font2)

        lyrics3 = wx.StaticText(panel, -1, text3,(10, 220), style=wx.ALIGN_CENTRE)
        lyrics3.SetFont(font3)

        #------------

        self.Center()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Fonts.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{attachment:fonts.png}}

'''Figure: fonts.py'''

=== Colours ===
A colour is an object representing a combination of Red, Green, and Blue (RGB) intensity values.  Valid RGB values are in the range 0 to 255.

There are three ways for setting colours. We can create a wx.Colour object, use a predefined colour name or  use hex value string.

{{{
SetBackgroundColour(wx.Colour(0,0,255))
SetBackgroundColour('BLUE')              # A predefined colour name .
SetBackgroundColour('#0000FF')           # Hex value string.
}}}
Predefined colour names in wxPython:

 * wx.BLACK
 * wx.WHITE
 * wx.RED
 * wx.BLUE
 * wx.GREEN
 * wx.CYAN
 * wx.LIGHT_GREY

Standard colour database:

[[#head-dda5ab503215d8330883aa21c0a396add53bada8|Listed below.]]

colours.py script shows eight different colours. wxBlack is simple. sea green is poetic and #0000FF technical. It is up to the developer, what to choose.

{{{#!python
#!/usr/bin/python

# colours.py

import wx

#---------------------------------------------------------------------------

class Colours(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, size=(300, 300))

        self.pnl1 = wx.Panel(self, -1)
        self.pnl2 = wx.Panel(self, -1)
        self.pnl3 = wx.Panel(self, -1)
        self.pnl4 = wx.Panel(self, -1)
        self.pnl5 = wx.Panel(self, -1)
        self.pnl6 = wx.Panel(self, -1)
        self.pnl7 = wx.Panel(self, -1)
        self.pnl8 = wx.Panel(self, -1)

        #------------

        vbox = wx.BoxSizer(wx.VERTICAL)

        gs = wx.GridSizer(4,2,3,3)
        gs.AddMany([ (self.pnl1, 0 ,wx.EXPAND),
            (self.pnl2, 0, wx.EXPAND),
            (self.pnl3, 0, wx.EXPAND),
            (self.pnl4, 0, wx.EXPAND),
            (self.pnl5, 0, wx.EXPAND),
            (self.pnl6, 0, wx.EXPAND),
            (self.pnl7, 0, wx.EXPAND),
            (self.pnl8, 0, wx.EXPAND) ])

        vbox.Add(gs, 1, wx.EXPAND | wx.TOP, 5)
        self.SetSizer(vbox)

        #------------

        self.SetColors()

        #------------

        self.Centre()

        #------------

        self.ShowModal()
        self.Destroy()

    #-----------------------------------------------------------------------

    def SetColors(self):
        self.pnl1.SetBackgroundColour(wx.BLACK)
        self.pnl2.SetBackgroundColour(wx.Colour(139,105,20))
        self.pnl3.SetBackgroundColour(wx.RED)
        self.pnl4.SetBackgroundColour('#0000FF')
        self.pnl5.SetBackgroundColour('sea green')
        self.pnl6.SetBackgroundColour('midnight blue')
        self.pnl7.SetBackgroundColour(wx.LIGHT_GREY)
        self.pnl8.SetBackgroundColour('plum')

#---------------------------------------------------------------------------

app = wx.App(0)
Colours(None, -1, 'Colours.py')
app.MainLoop()
}}}
{{attachment:colours.png}}

'''Figure: colours.py'''

The full database has currently about 630 different colour names. The list can be found in the colourdb.py file. It is also shown in the wxPython demo. In randomcolours.py script we have a single window. We change the background colour of the window to the randomly chosen colour.

{{{#!python
#!/usr/bin/python

# randomcolours.py

import wx

from random import randrange
from wx.lib.colourdb import *

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(400, 350))

        self.panel = wx.Panel(self, -1)

        self.colors = getColourList()
        self.col_num = len(self.colors)

        #------------

        self.timer = wx.Timer(self)
        self.timer.Start(1500)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnTimer(self, event):
        self.panel.SetBackgroundColour(wx.RED)
        position = randrange(0, self.col_num-1, 1)
        self.panel.SetBackgroundColour(self.colors[position])
        self.panel.Refresh()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        updateColourDB()
        frame = MyFrame(None, -1, 'Randomcolours.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
=== Bitmaps ===
There are two kinds of graphics. '''Vector''' and '''bitmap'''.  With vector graphics, images are created with mathematical formulas that define all the shapes of the image. Geometric objects like curves and polygons are used.  A bitmap or a bit map is a collection of bits that form an image. It is a grid of individual dots stored in memory or in a file. Each dot has its own colour. When the image is displayed, the computer transfers a bit map into pixels on monitors or ink dots on printers. The quality of a bitmap is determined by the '''resolution''' and the '''color depth''' of the image.  The resolution is the total number of pixels in the image. The Color depth is the amount of information in each pixel.

There are various kinds of bitmaps:

 * PNG
 * JPEG
 * GIF
 * TIFF
 * BMP

{{{#!python
#!/usr/bin/python

# bitmap.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(320, 300))

        self.bitmap = wx.Bitmap('memento.jpg')

        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.Centre()

    #-----------------------------------------------------------------------

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.bitmap, 80, 20)

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'bitmap.py (Memento)')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{attachment:memento.png}}

'''Figure: bitmap.py'''

== Events ==
Events are integral part of every GUI application. All GUI applications are event-driven. An application reacts to different event types which are generated during its life. Events are generated mainly by the user of an application.  But they can be generated by other means as well. e.g. internet connection, window manager, timer.  So when we call {{{MainLoop()}}} method, our application waits for events to be generated. The {{{MainLoop()}}} method ends when we exit the application.

Working with events is straightforward in wxPython. There are three steps:

 * Identify the event name: wx.EVT_SIZE, wx.EVT_CLOSE etc
 * Create an event handler. It is a method, that is called, when an event is generated
 * Bind an event to an event handler.

In wxPython we say to bind a method to an event. Sometimes a word hook is used.

You bind an event by calling the {{{Bind()}}} method. The method has the following parameters:

{{{
Bind(event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY)
}}}
 * event is one of EVT_* objects. It specifies the type of the event.
 * handler is an object to be called. In other words, it is a method, that a programmer binds to an event.
 * source parameter is used when we want to differentiate between the same event type from different widgets.
 * id parameter is used, when we have multiple buttons, menu items etc.  The id is used to differentiate among them.
 * id2 is used when it is desirable to bind a handler to a range of ids, such as with EVT_MENU_RANGE.

Note that method {{{Bind()}}} is defined in class {{{EvtHandler}}}. It is the class, from which wx.Window inherits. wx.Window is a base class for most widgets in wxPython. There is also a reverse process. If we want to unbind a method from an event, we call the {{{Unbind()}}} method. It has the same paremeters as the above one.
||||<style="text-align:center;">'''Possible events''' ||
||<#d0d0d0>{{{wx.Event}}} ||<#d0d0d0>the event base class ||
||{{{wx.ActivateEvent}}} ||a window or application activation event ||
||<#d0d0d0>{{{wx.CloseEvent}}} ||<#d0d0d0>a close window or end session event ||
||{{{wx.EraseEvent}}} ||an erase background event ||
||<#d0d0d0>{{{wx.FocusEvent}}} ||<#d0d0d0>a window focus event ||
||{{{wx.KeyEvent}}} ||a keypress event ||
||<#d0d0d0>{{{wx.IdleEvent}}} ||<#d0d0d0>an idle event ||
||{{{wx.InitDialogEvent}}} ||a dialog initialisation event ||
||<#d0d0d0>{{{wx.JoystickEvent}}} ||<#d0d0d0>a joystick event ||
||{{{wx.MenuEvent}}} ||a menu event ||
||<#d0d0d0>{{{wx.MouseEvent}}} ||<#d0d0d0>a mouse event ||
||{{{wx.MoveEvent}}} ||a move event ||
||<#d0d0d0>{{{wx.PaintEvent}}} ||<#d0d0d0>a paint event ||
||{{{wx.QueryLayoutInfoEvent}}} ||used to query layout information ||
||<#d0d0d0>{{{wx.SetCursorEvent}}} ||<#d0d0d0>used for special cursor processing based on current mouse position ||
||{{{wx.SizeEvent}}} ||a size event ||
||<#d0d0d0>{{{wx.ScrollWinEvent}}} ||<#d0d0d0>a scroll event sent by a built-in Scrollbar ||
||{{{wx.ScrollEvent}}} ||a scroll event sent by a stand-alone scrollbar ||
||<#d0d0d0>{{{wx.SysColourChangedEvent}}} ||<#d0d0d0>a system colour change event ||




=== Examples ===
The following code is an example of a {{{wx.ScrollWinEvent}}}. This event is generated, when we click on a built in Scrollbar. Built-in Scrollbar is activated with the {{{SetScrollbar()}}} method call. For stand-alone Scrollbars, there is another event type, namely {{{wx.ScrollEvent}}}.

{{{#!python
#!/usr/bin/python

# myscrollwinevent.py

import wx

#---------------------------------------------------------------------------

class MyScrollWinEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        panel = wx.Panel(self, -1)
        panel.SetScrollbar(wx.VERTICAL, 0, 6, 50)
        panel.Bind(wx.EVT_SCROLLWIN, self.OnScroll)

        self.st = wx.StaticText(panel, -1, '0', (30, 0))

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnScroll(self, evt):
        y = evt.GetPosition()
        self.st.SetLabel(str(y))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        msw = MyScrollWinEvent(None, -1, 'Myscrollwinevent.py')
        msw.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
The {{{wx.SizeEvent}}} is generated, when our window is resized. In our example, we show the size of the window in the titlebar.

{{{#!python
#!/usr/bin/python

# sizeevent.py

import wx

#---------------------------------------------------------------------------

class SizeEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        #------------

        self.Bind(wx.EVT_SIZE, self.OnSize)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnSize(self, event):
        self.SetTitle(str("Size : %s" % event.GetSize()))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        se = SizeEvent(None, -1, 'Sizeevent.py')
        se.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{{#!python
#!/usr/bin/python

# moveevent.py

import wx

#---------------------------------------------------------------------------

class MoveEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        wx.StaticText(self, -1, 'x:', (10,0))
        wx.StaticText(self, -1, 'y:', (10,20))

        self.st1 = wx.StaticText(self, -1, '', (30, 0))
        self.st2 = wx.StaticText(self, -1, '', (30, 20))

        #------------

        self.Bind(wx.EVT_MOVE, self.OnMove)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnMove(self, event):
        x, y = event.GetPosition()
        self.st1.SetLabel(str(x))
        self.st2.SetLabel(str(y))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        me = MoveEvent(None, -1, 'Moveevent.py')
        me.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
A paint event is generated when a window is redrawn. This happens when we resize window, maximize it. A paint event can be generated programatically as well. For example, when we call {{{SetLabel()}}} method to change a {{{wxStaticText}}} widget. Note that when we minimize a window, no paint event is generated.

{{{#!python
#!/usr/bin/python

# paintevent.py

import wx

#---------------------------------------------------------------------------

class PaintEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.Bind(wx.EVT_PAINT, self.OnPaint)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnPaint(self, event):
        wx.Bell()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        pe = PaintEvent(None, -1, 'Paintevent.py')
        pe.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
When we press a key on our keyboard, {{{wx.KeyEvent}}} is generated. There are three different key handlers:

 * EVT_KEY_DOWN
 * EVT_KEY_UP
 * EVT_CHAR

A common request is to close application, when Esc key is pressed.

{{{#!python
#!/usr/bin/python

# keyevent.py

import wx

#---------------------------------------------------------------------------

class KeyEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        panel = wx.Panel(self, -1)
        panel.SetFocus()
        panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

        #------------

        self.Centre()

        #------------

        self.Show(True)

    #-----------------------------------------------------------------------

    def OnKeyDown(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_ESCAPE:
            ret  = wx.MessageBox('Are you sure to quit?',
                                 'Question',
                                 wx.YES_NO | wx.CENTRE |
                                 wx.NO_DEFAULT,
                                 self)
            if ret == wx.YES:
                self.Close()
        event.Skip()

#---------------------------------------------------------------------------

app = wx.App()
KeyEvent(None, -1, 'Keyevent.py')
app.MainLoop()
}}}
We find out, which key was pressed by calling {{{GetKeyCode()}}} method. In our case, keycode is wx.WXK_ESCAPE.

{{{
keycode = event.GetKeyCode()
}}}
Other keycodes are [[#head-999ff1e3fbf5694a51a91cf4ed2140f692da013c|listed below.]]

== Dialogs ==
In wxPython  you can use predefined dialogs or create your own dialogs. You can also create dialog based applications.

The example shows a skeleton of a dialog based application in wxPython.

{{{#!python
#!/usr/bin/python

# simpledialog.py

import wx

#---------------------------------------------------------------------------

class MyDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title)

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        dia = MyDialog(None, -1, "Simpledialog.py")
        dia.ShowModal()
        dia.Destroy()

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
Notice that you cannot resize the dialog window.  The {{{Destroy()}}} method is necessary. It deletes the dialog from the memory. Otherwise, the script would not exit properly.

There are two types of dialogs. Modal and modeless. Modal dialog does not allow a user to work with the rest of the application until it is destroyed. Modal dialogs are created with the {{{ShowModal()}}} method. Dialogs are modeless  when called with {{{Show()}}}.

=== Custom dialogs ===
There are two methods that simplify the creation of dialogs.  Both return a specific sizer object.

{{{
CreateTextSizer(self, string message)
CreateButtonSizer(self, long flags)
}}}
{{{CreateTextSizer()}}} method creates a text sizer.  In the following example, we add some buttons into the sizer to demonstrate it.

{{{#!python
#!/usr/bin/python

# customdialog1.py

import wx

#---------------------------------------------------------------------------

class MyDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, size=(300, 250))

        sizer = self.CreateTextSizer(' My Buttons :')

        sizer.Add(wx.Button(self, -1, 'Button 1'), 0, wx.ALL, 5)
        sizer.Add(wx.Button(self, -1, 'Button 2'), 0, wx.ALL, 5)
        sizer.Add(wx.Button(self, -1, 'Button 3'), 0, wx.ALL, 5)
        sizer.Add(wx.Button(self, -1, 'Button 4'), 0, wx.ALL|wx.ALIGN_CENTER, 5)
        sizer.Add(wx.Button(self, -1, 'Button 5'), 0, wx.ALL|wx.EXPAND, 5)

        self.SetSizer(sizer)

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 300))

        panel = wx.Panel(self, -1)

        wx.Button(panel, 1, 'Show Custom Dialog', (100, 100))

        self.Bind (wx.EVT_BUTTON, self.OnShowCustomDialog, id=1)

    #-----------------------------------------------------------------------

    def OnShowCustomDialog(self, event):
        dia = MyDialog(self, -1, 'buttons')
        dia.ShowModal()
        dia.Destroy()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Customdialog1.py')
        frame.Centre()
        frame.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{{CreateButtonSizer()}}} method creates a row of buttons. You can specify button types with different flags. {{{CreateButtonSizer()}}} method can take the following flags:

 * wx.OK
 * wx.CANCEL
 * wx.YES
 * wx.NO
 * wx.HELP
 * wx.NO_DEFAULT

{{{#!python
#!/usr/bin/python

# customdialog2.py

import wx

#---------------------------------------------------------------------------

class MyDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title)

        stline = wx.StaticText(self, -1, 'Discipline ist Macht.')

        sizer =  self.CreateButtonSizer(wx.NO | wx.YES | wx.HELP)

        #------------

        vbox = wx.BoxSizer(wx.VERTICAL)

        vbox.Add(stline, 1, wx.ALIGN_CENTER|wx.TOP, 45)
        vbox.Add(sizer, 0, wx.ALIGN_CENTER | wx.ALL, 10)

        self.SetSizer(vbox)

        #------------

        self.Bind(wx.EVT_BUTTON, self.OnYes, id=wx.ID_YES)

    #-----------------------------------------------------------------------

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

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        panel = wx.Panel(self, -1)

        wx.Button(panel, 1, '&Show custom Dialog', (50, 50))

        self.Bind(wx.EVT_BUTTON, self.OnShowCustomDialog, id=1)

    #-----------------------------------------------------------------------

    def OnShowCustomDialog(self, event):
        dia = MyDialog(self, -1, '')
        val = dia.ShowModal()
        dia.Destroy()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Customdialog2.py')
        frame.Centre()
        frame.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
Note that wxPython does not take the order of flags into account.

{{{
sizer =  self.CreateButtonSizer(wxNO|wxYES|wxHELP)
}}}
The buttons will be created according to the standards.

=== Common Predefined Dialogs ===
wxPython provides several common dialogs. They save programmers a lot of work. They also help promote standards in applications. We will show these ones:

 * {{{wx.MessageDialog}}}
 * {{{wx.ColourDialog}}}
 * {{{wx.FileDialog}}}
 * {{{wx.PageSetupDialog}}}
 * {{{wx.FontDialog}}}
 * {{{wx.DirDialog}}}
 * {{{wx.SingleChoiceDialog}}}
 * {{{wx.TextEntryDialog}}}

{{{#!python
#!/usr/bin/python

# commondialogs.py

import wx
import os, sys

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.CreateStatusBar()

        #------------

        menuBar = wx.MenuBar()

        menu = wx.Menu()
        menu.Append(99,  "&Message Dialog", "Shows a Message Dialog")
        menu.Append(100, "&Color Dialog", "Shows a Color Dialog")
        menu.Append(101, "&File Dialog", "Shows a File Dialog")
        menu.Append(102, "&Page Setup Dialog", "Shows a Page Setup Dialog")
        menu.Append(103, "&Font Dialog", "Shows a Font Dialog")
        menu.Append(104, "&Directory Dialog", "Shows a Directory Dialog")
        menu.Append(105, "&SingleChoice Dialog", "Shows a SingleChoice Dialog")
        menu.Append(106, "&TextEntry Dialog", "Shows a TextEntry Dialog")
        menuBar.Append(menu, "&Dialogs")

        self.SetMenuBar(menuBar)

        #------------

        self.Bind(wx.EVT_MENU, self.message, id=99)
        self.Bind(wx.EVT_MENU, self.choosecolor, id=100)
        self.Bind(wx.EVT_MENU, self.openfile, id=101)
        self.Bind(wx.EVT_MENU, self.pagesetup, id=102)
        self.Bind(wx.EVT_MENU, self.choosefont, id=103)
        self.Bind(wx.EVT_MENU, self.opendir, id=104)
        self.Bind(wx.EVT_MENU, self.singlechoice, id=105)
        self.Bind(wx.EVT_MENU, self.textentry, id=106)

    #-----------------------------------------------------------------------

    def message(self, event):
        dlg = wx.MessageDialog(self, 'To save one life is as if you have saved the world.', 'Talmud', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()


    def choosecolor(self, event):
        dlg = wx.ColourDialog(self)
        dlg.GetColourData().SetChooseFull(True)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
            self.SetStatusText('You selected: %s\n' % str(data.GetColour().Get()))
        dlg.Destroy()


    def openfile(self, event):
        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            mypath = os.path.basename(path)
            self.SetStatusText("You selected: %s" % mypath)
        dlg.Destroy()


    def pagesetup(self, event):
        dlg = wx.PageSetupDialog(self)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetPageSetupData()
            tl = data.GetMarginTopLeft()
            br = data.GetMarginBottomRight()
            self.SetStatusText('Margins are: %s %s' % (str(tl), str(br)))
        dlg.Destroy()


    def choosefont(self, event):
        default_font = wx.Font(10, wx.SWISS , wx.NORMAL, wx.NORMAL, False, "Verdana")
        data = wx.FontData()
        if sys.platform == 'win32':
            data.EnableEffects(True)
        data.SetAllowSymbols(False)
        data.SetInitialFont(default_font)
        data.SetRange(10, 30)
        dlg = wx.FontDialog(self, data)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetFontData()
            font = data.GetChosenFont()
            color = data.GetColour()
            text = 'Face: %s, Size: %d, Color: %s' % (font.GetFaceName(), font.GetPointSize(),  color.Get())
            self.SetStatusText(text)
        dlg.Destroy()


    def opendir(self, event):
        dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if dlg.ShowModal() == wx.ID_OK:
            self.SetStatusText('You selected: %s\n' % dlg.GetPath())
        dlg.Destroy()


    def singlechoice(self, event):
        sins = ['Greed', 'Lust', 'Gluttony', 'Pride', 'Sloth', 'Envy', 'Wrath']
        dlg = wx.SingleChoiceDialog(self, 'Seven deadly sins', 'Which one?', sins, wx.CHOICEDLG_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.SetStatusText('You chose: %s\n' % dlg.GetStringSelection())
        dlg.Destroy()


    def textentry(self, event):
        dlg = wx.TextEntryDialog(self, 'Enter some text','Text Entry')
        dlg.SetValue("Default")
        if dlg.ShowModal() == wx.ID_OK:
            self.SetStatusText('You entered: %s\n' % dlg.GetValue())
        dlg.Destroy()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        myframe = MyFrame(None, -1, "Commondialogs.py")
        myframe.CenterOnScreen()
        myframe.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
The script shows eight different common dialogs. All the output is displayed on the statusbar.

{{attachment:messagedialog.png}}  {{attachment:textentrydialog.png}} <<BR>> <<BR>> {{attachment:fontdialog.png}} {{attachment:colordialog.png}} <<BR>> <<BR>> {{attachment:directorydialog.png}} {{attachment:filedialog.png}} <<BR>> <<BR>> {{attachment:pagesetupdialog.png}} {{attachment:singlechoicedialog.png}}

'''Figure: commondialogs.py'''

== Core Widgets ==
In this section, we will introduce basic widgets in wxPython. Each widget will have a small code example.

=== wx.Button ===
link : [[https://wiki.wxpython.org/How%20to%20create%20a%20button%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20button%20%28Phoenix%29]]

{{attachment:buttons.png}}

'''Figure: buttons.py'''

=== wx.ToggleButton ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20toggle%20button%20%28Phoenix%29

{{attachment:togglebuttons.png}}

'''Figure: togglebuttons.py'''

=== wx.BitmapButton ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20bitmap%20button%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20bitmap%20button%20%28Phoenix%29]]

{{attachment:player.png}}

'''Figure: player.py'''

=== wx.StaticLine ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20static%20line%20%28Phoenix%29

{{attachment:centraleurope.png}}

'''Figure: centraleurope.py'''

=== wx.StaticText ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20static%20text%20%28Phoenix%29

{{attachment:statictext.png}}

'''Figure: ''''''statictext.py'''

=== wx.StaticBox ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20static%20box%20%28Phoenix%29

{{attachment:staticbox.png}}

'''Figure: ''''''staticbox.py'''

=== wx.ComboBox ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20combo%20box%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20combo%20box%20%28Phoenix%29]]

{{attachment:combobox.png}}

'''Figure: combobox.py'''

=== wx.CheckBox ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20check%20box%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20check%20box%20%28Phoenix%29]]

{{attachment:checkbox.png}}

'''Figure: checkbox.py'''

=== wx.StatusBar ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20status%20bar%20%28Phoenix%29

{{attachment:statusbar.png}}

'''Figure: statusbar.py'''

=== wx.RadioButton ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20radio%20button%20%28Phoenix%29

{{attachment:radiobuttons.png}}

'''Figure: radiobuttons.py'''

=== wx.Gauge ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20gauge%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20gauge%20%28Phoenix%29]]

{{attachment:gauge.png}}

'''Figure: gauge.py'''

=== wx.Slider ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20slider%20%28Phoenix%29

{{attachment:slider.png}}

'''Figure: slider.py'''

=== wx.ListBox ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20list%20box%20%28Phoenix%29

{{attachment:listbox.png}}

'''Figure: listbox.py'''

=== wx.SpinCtrl ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20spin%20control%20%28Phoenix%29

{{attachment:spinctrl.png}}

'''Figure: ''''''spinctrl.py'''

=== wx.ListCtrl ===
{{{wx.ListCtrl}}} creates lists in the following formats:

 * report view
 * list view
 * icon view

In our example, we key in the states and their capitals and add them into the list widget. We use report view.

{{{#!python
#!/usr/bin/python

# capitals.py

import wx

#---------------------------------------------------------------------------

class MyDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title,
                           size=(600, 500), style=wx.DEFAULT_DIALOG_STYLE)

        pnl1 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        pnl2 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)

        self.lc = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
        self.lc.InsertColumn(0, 'State')
        self.lc.InsertColumn(1, 'Capital')
        self.lc.SetColumnWidth(0, 140)
        self.lc.SetColumnWidth(1, 153)
        self.lc.SetBackgroundColour("#eceade")

        self.tc1 = wx.TextCtrl(pnl1, -1)
        self.tc2 = wx.TextCtrl(pnl1, -1)

        #------------

        hbox  = wx.BoxSizer(wx.HORIZONTAL)
        vbox1 = wx.BoxSizer(wx.VERTICAL)
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        vbox3 = wx.GridSizer(2,2,0,0)
        vbox4 = wx.BoxSizer(wx.VERTICAL)

        vbox1.Add(pnl1, 1, wx.EXPAND | wx.ALL, 3)
        vbox1.Add(pnl2, 1, wx.EXPAND | wx.ALL, 3)

        vbox2.Add(self.lc, 1, wx.EXPAND | wx.ALL, 3)

        vbox3.AddMany([ (wx.StaticText(pnl1, -1, 'State :'),0, wx.ALIGN_CENTER),
                        (self.tc1, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL),
                        (wx.StaticText(pnl1, -1, 'Capital :'),0, wx.ALIGN_CENTER_HORIZONTAL),
                        (self.tc2,0)])

        vbox4.Add(wx.Button(pnl2, 10, '&Add'),   0, wx.ALIGN_CENTER| wx.TOP, 45)
        vbox4.Add(wx.Button(pnl2, 11, '&Remove'), 0, wx.ALIGN_CENTER|wx.TOP, 15)
        vbox4.Add(wx.Button(pnl2, 12, '&Clear'), 0, wx.ALIGN_CENTER| wx.TOP, 15)
        vbox4.Add(wx.Button(pnl2, 13, '&Quit'), 0, wx.ALIGN_CENTER| wx.TOP, 15)

        hbox.Add(vbox1, 1, wx.EXPAND)
        hbox.Add(vbox2, 1, wx.EXPAND)

        pnl1.SetSizer(vbox3)
        pnl2.SetSizer(vbox4)
        self.SetSizer(hbox)

        #------------

        self.Bind (wx.EVT_BUTTON, self.OnAdd, id=10)
        self.Bind (wx.EVT_BUTTON, self.OnRemove, id=11)
        self.Bind (wx.EVT_BUTTON, self.OnClear, id=12)
        self.Bind (wx.EVT_BUTTON, self.OnClose, id=13)

    #-----------------------------------------------------------------------

    def OnAdd(self, event):
        if not self.tc1.GetValue() or not self.tc2.GetValue():
            return
        num_items = self.lc.GetItemCount()
        self.lc.InsertItem(num_items, self.tc1.GetValue())
        self.lc.SetItem(num_items, 1, self.tc2.GetValue())
        self.tc1.Clear()
        self.tc2.Clear()


    def OnRemove(self, event):
        index = self.lc.GetFocusedItem()
        self.lc.DeleteItem(index)


    def OnClose(self, event):
        self.Close()


    def OnClear(self, event):
        self.lc.DeleteAllItems()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        dia = MyDialog(None, -1, 'Capitals.py')
        dia.ShowModal()
        dia.Destroy()

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{attachment:capitals1.png}}

'''Figure: capitals.py'''

=== wx.SplitterWindow ===
This widget enables to split the main area of an application into parts. The user can dynamically resize those parts with the mouse pointer. Such a solution can be seen in mail clients (evolution) or in burning software (k3b). You can split an area vertically or horizontally.

{{{#!python
#!/usr/bin/python

# splitterwindow.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(350, 300))

        splitter = wx.SplitterWindow(self, -1)
        splitter.SetMinimumPaneSize(20)

        panel1 = wx.Panel(splitter, -1)
        panel1.SetBackgroundColour(wx.LIGHT_GREY)

        wx.StaticText(panel1, -1,
                      "Whether you think that you can, or that you can't, you are usually right."
                      "\n\n Henry Ford",
                      (100,100), style=wx.ALIGN_CENTRE)

        panel2 = wx.Panel(splitter, -1)
        panel2.SetBackgroundColour(wx.YELLOW)

        splitter.SplitVertically(panel1, panel2)

        #------------

        self.Centre()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Splitterwindow.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
=== wx.ScrolledWindow ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20scrolled%20window%20%28Phoenix%29

{{attachment:scrolledwindow.png}}

'''Figure: myscrolledwindow.py'''

=== wx.TreeCtrl ===
{{{wx.TreeCtrl}}} displays data in a hierarchy.

{{{#!python
#!/usr/bin/python

# treectrl.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(450, 350))

        panel1 = wx.Panel(self, -1)
        panel2 = wx.Panel(self, -1)

        self.tree = wx.TreeCtrl(panel1, 1, wx.DefaultPosition, (-1,-1),
                                wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)

        root = self.tree.AddRoot('Programmer')
        os = self.tree.AppendItem(root, 'Operating Systems')
        pl = self.tree.AppendItem(root, 'Programming Languages')
        tk = self.tree.AppendItem(root, 'Toolkits')

        self.tree.AppendItem(os, 'Linux')
        self.tree.AppendItem(os, 'FreeBSD')
        self.tree.AppendItem(os, 'OpenBSD')
        self.tree.AppendItem(os, 'NetBSD')
        self.tree.AppendItem(os, 'Solaris')

        cl = self.tree.AppendItem(pl, 'Compiled languages')
        sl = self.tree.AppendItem(pl, 'Scripting languages')

        self.tree.AppendItem(cl, 'Java')
        self.tree.AppendItem(cl, 'C++')
        self.tree.AppendItem(cl, 'C')
        self.tree.AppendItem(cl, 'Pascal')
        self.tree.AppendItem(sl, 'Python')
        self.tree.AppendItem(sl, 'Ruby')
        self.tree.AppendItem(sl, 'Tcl')
        self.tree.AppendItem(sl, 'PHP')
        self.tree.AppendItem(tk, 'Qt')
        self.tree.AppendItem(tk, 'MFC')
        self.tree.AppendItem(tk, 'wxPython')
        self.tree.AppendItem(tk, 'GTK+')
        self.tree.AppendItem(tk, 'Swing')
        self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)

        self.display = wx.StaticText(panel2, -1, '',(10, 10), style=wx.ALIGN_CENTRE)

        #------------

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)

        vbox.Add(self.tree, 1, wx.EXPAND)

        hbox.Add(panel1, 1, wx.EXPAND)
        hbox.Add(panel2, 1, wx.EXPAND)

        panel1.SetSizer(vbox)
        self.SetSizer(hbox)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnSelChanged(self, event):
        item =  event.GetItem()
        self.display.SetLabel(self.tree.GetItemText(item))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Treectrl.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
First of all we must create a root item.

{{{
root = self.tree.AddRoot('Programmer')
}}}
In our case, root item will not be displayed, because we used wx.TR_HIDE_ROOT flag in our constructor.

{{{
self.tree = wx.TreeCtrl(panel1, 1, wx.DefaultPosition, (-1,-1), wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)
}}}
We add items to the root item with{{{AppendItem()}}} method.

{{{
os = self.tree.AppendItem(root, 'Operating Systems')
pl = self.tree.AppendItem(root, 'Programming Languages')
tk = self.tree.AppendItem(root, 'Toolkits')
}}}
We can similarly create several levels by simply adding items to existing items.

We catch events with wx.EVT_TREE_SEL_CHANGED() event handler.

{{{
wx.EVT_TREE_SEL_CHANGED(self.tree, 1, self.OnSelChanged)
}}}
Various constructor style flags:

 * TR_NO_BUTTONS
 * TR_HAS_BUTTONS
 * TR_NO_LINES
 * TR_LINES_AT_ROOT
 * TR_SINGLE
 * TR_MULTIPLE
 * TR_EXTENDED
 * TR_HAS_VARIABLE_ROW_HEIGHT
 * TR_EDIT_LABELS
 * TR_HIDE_ROOT
 * TR_ROW_LINES
 * TR_FULL_ROW_HIGHLIGHT
 * TR_DEFAULT_STYLE
 * TR_TWIST_BUTTONS
 * TR_MAC_BUTTONS
 * TR_AQUA_BUTTONS

{{attachment:treecontrol.png}}

'''Figure: treectrl.py'''

=== wx.Notebook ===

Link :
https://wiki.wxpython.org/How%20to%20create%20a%20notebook%20%28Phoenix%29

{{attachment:notebook.png}}

'''Figure: notebook.py'''

== wx.lib Classes ==
Link :
https://wiki.wxpython.org/wxPython%20snippets%2C%20examples%2C%20tutorials%2C%20links...%20%28Phoenix%29

=== Mouse Gestures ===
We can find mouse gestures in such successfull applications like Firefox or Opera. They really help users save their time while browsing on the Interent. Mouse gestures are created with

{{{wx.lib.gestures.MouseGestures}}} class in wxPython. <<BR>> <<BR>>
||||<style="text-align:center;">'''{{{Possible methods}}}''' ||
||<#d0d0d0>{{{AddGesture(string gesture, action)}}} ||<#d0d0d0>registers a mouse gesture ||
||{{{RemoveGesture(string gesture)}}} ||removes a mouse gesture ||
||<#d0d0d0>{{{SetGesturePen(wx.Colour colour, integer width)}}} ||<#d0d0d0>sets the colour and width of the line drawn to visually represent each gesture ||
||{{{SetGesturesVisible(boolean vis)}}} ||sets wether a line is drawn to visually represent each gesture ||
||<#d0d0d0>{{{SetWobbleTolerance(integer wobbletolerance)}}} ||<#d0d0d0>sets the intensity to trigger a gesture ||
||{{{SetModifiers(list modifiers)}}} ||takes a list of wx.Key constants (Control, Shift, and/or Alt) ||
||<#d0d0d0>{{{SetMouseButton(integer flag)}}} ||<#d0d0d0>takes the wx constant for the target mousebutton ||




Available gestures:

 * L for left
 * R for right
 * U for up
 * D for down
 * 7 for northwest
 * 9 for northeast
 * 1 for southwest
 * 3 for southeast

If you wonder why these numbers were chosen, have a look at the numerical pad. Mouse gestures can be combined. This way 'RDLU' is a mouse gesture triggered, when we do a square with a mouse pointer.

Possible flags are:

 * wx.MOUSE_BTN_LEFT
 * wx.MOUSE_BTN_MIDDLE
 * wx.MOUSE_BTN_RIGHT

{{{#!python
#!/usr/bin/python

# mousegestures.py

import wx
import wx.lib.gestures as gest

#---------------------------------------------------------------------------

class MyMouseGestures(wx.Frame):
    def __init__ (self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600, 500))

        panel = wx.Panel(self, -1)

        mg = gest.MouseGestures(panel, True, wx.MOUSE_BTN_LEFT)
        mg.SetGesturePen(wx.Colour(255, 0, 0), 2)
        mg.SetGesturesVisible(True)
        mg.AddGesture('DR', self.OnDownRight)

    #-----------------------------------------------------------------------

    def OnDownRight(self):
          self.Close()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyMouseGestures(None, -1, "Mousegestures.py")
        frame.Show(True)
        frame.Centre()

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
In our example, we have registered a mouse gesture for a panel. Mouse gesture is triggered, when a left button is pressed and we go down and right with a cursor. As in letter 'L'. Our mouse gesture will close the application. If we want to use mouse gestures, we have to create a

{{{MouseGesture object}}}. The first parameter is a window, where the mouse gesture is  registered. Second parameter defines a way to register a gesture. True is for automatic, False for manual. Manual is not fully implemented and we are happy with the automatic way. Last parameter defines a mouse button, which will be pressed when triggering gestures. The button can be later changed with the {{{SetMouseButton()}}} method.

{{{
mg = gest.MouseGestures(panel, True, wx.MOUSE_BTN_LEFT)
}}}
Our gestures will be painted as red lines. They will be 2 pixels wide.

{{{
mg.SetGesturePen(wx.Colour(255, 0, 0), 2)
}}}
We set this gesture visible with the{{{SetGesturesVisible()}}} method.

{{{
mg.SetGesturesVisible(True)
}}}
We register a mouse gesture with the{{{AddGesture()}}} method. The first parameter is the gesture. Second parameter is the method triggered by the gesture.

{{{
mg.AddGesture('DR', self.OnDownRight)
}}}
=== AnalogClockWindow ===
Simple analog clock.

{{{#!python
#!/usr/bin/python

# analogclock.py

import wx
from wx.lib import analogclock as ac

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        #------------

        if wx.Platform == "__WXMSW__":
            self.SetDoubleBuffered(True)

        #------------

        clock = ac.AnalogClockWindow(self)
        clock.SetBackgroundColour('gray')
        clock.SetHandColours('black')
        clock.SetTickColours('WHITE')
        clock.SetTickSizes(h=5, m=2)
        clock.SetTickStyles(ac.TICKS_ROMAN)

        #------------

        self.SetSize((400,350))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Analogclock.py')
        frame.Centre()
        frame.Show(True)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
Various clock styles:

{{{SetClockStyle()}}}

 * SHOW_QUARTERS_TICKS
 * SHOW_HOURS_TICKS
 * SHOW_MINUTES_TICKS
 * SHOW_HOURS_HAND
 * SHOW_MINUTES_HAND
 * SHOW_SECONDS_HAND
 * SHOW_SHADOWS
 * ROTATE_TICKS
 * OVERLAP_TICKS

Various ticks styles:

{{{SetTickStyles()}}}

 * TICKS_NONE
 * TICKS_SQUARE
 * TICKS_CIRCLE
 * TICKS_POLY
 * TICKS_DECIMAL
 * TICKS_ROMAN

{{attachment:analogclock.png}}

'''Figure: analogclock.py'''

=== Bitmap Text Buttons ===
Link :
https://wiki.wxpython.org/How%20to%20create%20a%20gen%20bitmap%20text%20button%20%28Phoenix%29

{{attachment:genbitmaptextbutton.png}}

'''Figure: genbitmaptextbutton.py'''

== Advanced Widgets ==
In this section we will discuss some advanced widgets. They are found in lib subdirectory which is in wx directory. These widgets are written in python. They address needs not covered by the underlying C++ wx library.

=== CalendarCtrl ===
CalendarCtrl is a handy widget for working with dates.

{{{#!python
#!/usr/bin/python

# calendar.py

import wx
import wx.adv
from wx.adv import CalendarCtrl, GenericCalendarCtrl, CalendarDateAttr

#---------------------------------------------------------------------------

class Calendar(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title)

        # calend = CalendarCtrl(self, -1, wx.DateTime().Today(),
        #                       style=wx.adv.CAL_SHOW_HOLIDAYS |
        #                             wx.adv.CAL_SEQUENTIAL_MONTH_SELECTION)
        # Or
        #
        calend = GenericCalendarCtrl(self, -1, wx.DateTime().Today(),
                                     style=wx.adv.CAL_SHOW_HOLIDAYS |
                                           wx.adv.CAL_SUNDAY_FIRST |
                                           wx.adv.CAL_SEQUENTIAL_MONTH_SELECTION)

        #------------

        self.text = wx.StaticText(self, -1, '&Date')
        btn = wx.Button(self, -1, '&Ok')

        #------------

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        hbox.Add(self.text)

        hbox2.Add(btn, 1)

        vbox.Add(calend, 0, wx.EXPAND | wx.ALL, 20)
        vbox.Add((-1, 20))
        vbox.Add(hbox, 0,  wx.LEFT, 8)
        vbox.Add(hbox2, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 20)

        self.SetSizerAndFit(vbox)

        #------------

        self.Bind(wx.adv.EVT_CALENDAR, self.OnCalSelected, id=calend.GetId())
        self.Bind(wx.EVT_BUTTON, self.OnQuit, id=btn.GetId())
        self.Bind(wx.EVT_CLOSE, self.OnQuit)

        #------------

        self.Centre()

        #------------

        self.Show(True)

    #-----------------------------------------------------------------------

    def OnCalSelected(self, event):
        date = event.GetDate()
        dt = str(date).split(' ')
        s = ' '.join(str(s) for s in dt)
        self.text.SetLabel(s)


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

#---------------------------------------------------------------------------

app = wx.App()
Calendar(None, -1, 'Calendar.py')
app.MainLoop()
}}}
Possible calendar styles:

[[#head-85c7edde1489f8719d30c09af56c2effd00a77c6|Listed below.]]

{{attachment:calendar.png}}

'''Figure: calendar.py'''

=== LEDNumberCtrl ===
In the previous example we had an analog clock example.{{{LEDNumberCtrl}}} widget displays a digital clock.

In our example we show current local time in a simple wx.Frame.

{{{#!python
#!/usr/bin/python

# lednumber.py

import time
import wx
import wx.gizmos as gizmos

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(450, 100))

        #------------

        if wx.Platform == "__WXMSW__":
            self.SetDoubleBuffered(True)

        #------------

        self.led = gizmos.LEDNumberCtrl(self, -1, wx.DefaultPosition,
                                        wx.DefaultSize, gizmos.LED_ALIGN_CENTER)

        self.OnTimer(None)
        self.timer = wx.Timer(self, -1)
        self.timer.Start(1000)
        self.Bind(wx.EVT_TIMER, self.OnTimer)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnTimer(self, event):
        t = time.localtime(time.time())
        st = time.strftime("%I:%M:%S", t)
        self.led.SetValue(st)

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Lednumber.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
Possible flags:

 * LED_ALIGN_LEFT
 * LED_ALIGN_RIGHT
 * LED_ALIGN_CENTER
 * LED_ALIGN_MASK
 * LED_DRAW_FADED

Windows users, put{{{wx.CallAfter()}}} in your code:

{{{
self.led = gizmos.LEDNumberCtrl(self, -1, style=gizmos.LED_ALIGN_CENTER)
wx.CallAfter(self.OnTimer, None)
self.timer = wx.Timer(self, -1)
}}}
{{attachment:lednumber.png}}

'''Figure: lednumber.py'''

== Creating a taskbar application ==
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20task%20bar%20icon%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20a%20task%20bar%20icon%20%28Phoenix%29]]

{{attachment:taskbaricon.png}}

'''Figure: mytaskbaricon.py'''

== wx.TheClipboard ==
From wikipedia:

In computing, the clipboard is a portion of memory where information that has been copied or cut from a computer application is stored. This storage is meant as a short-term volatile place to keep information that will be used again shortly.

{{{wx.TheClipboard}}} is a class for manipulating clipboard in wxPython. Fist we must call the Open() method to get ownership of the clipboard. If successful, the method returns true. Then we put data on the clipboard with the

{{{SetData()}}} method.  This method accepts a simple data object.

We have three predefined simple data objects:

 * {{{wx.FileDataObject}}}
 * {{{wx.TextDataObject}}}
 * {{{wx.BitmapDataObject}}}

To retrieve data from Clipboard you call method{{{GetData()}}}. It accepts simple data object as well. In the end we close the clipboard with {{{Close() }}}method and relinquish ownership of it.

{{{clipboard.py}}} example shows a simple usage of the the clipboard in wxPython.

{{{#!python
#!/usr/bin/python

# clipboard.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(320, 300))

        panel1 = wx.Panel(self, -1)

        self.tc1 = wx.TextCtrl(panel1, -1, '', (50,50), (85, -1))
        self.tc2 = wx.TextCtrl(panel1, -1, '', (180,50), (85, -1))

        wx.Button(panel1, 1, '&Copy', (50,200))
        wx.Button(panel1, 2, '&Paste', (180,200))

        #------------

        self.Bind(wx.EVT_BUTTON, self.OnCopy, id=1)
        self.Bind(wx.EVT_BUTTON, self.OnPaste, id=2)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnCopy(self, event):
        text = self.tc1.GetValue()
        if wx.TheClipboard.Open():
            wx.TheClipboard.Clear()
            wx.TheClipboard.SetData(wx.TextDataObject(text))
            wx.TheClipboard.Close()


    def OnPaste(self, event):
        if wx.TheClipboard.Open():
            td = wx.TextDataObject()
            success = wx.TheClipboard.GetData(td)
            wx.TheClipboard.Close()
            if not success: return
            text = td.GetText()
            if text: self.tc2.SetValue(text)

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Clipboard.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
We have two textcontrols and two buttons. We input some text into the first textcontrol and paste in the the second one with our two buttons. Notice how we retrieve data from the{{{wxTextDataObject}}}:

{{{
text = td.GetText()
}}}
== Drag and Drop ==
Wikipedia:

In computer graphical user interfaces, drag-and-drop is the action of (or support for the action of) clicking on a virtual object and dragging it to a different location or onto another virtual object. In general, it can be used to invoke many kinds of actions, or create various types of associations between two abstract objects. I think everyone is familiar with drag

& drop. Here is an example in wxPython:

{{{#!python
#!/usr/bin/python

# dragdrop.py

import os
import wx

#---------------------------------------------------------------------------

class MyTextDropTarget(wx.TextDropTarget):
    def __init__(self, object):
        wx.TextDropTarget.__init__(self)

        self.object = object

    #-----------------------------------------------------------------------

    def OnDropText(self, x, y, data):
        self.object.InsertItem(0, data)

        return True

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(600, 450))

        splitter1 = wx.SplitterWindow(self, -1, style=wx.SP_3D)
        splitter1.SetMinimumPaneSize(20)

        splitter2 = wx.SplitterWindow(splitter1, -1, style=wx.SP_3D)
        splitter2.SetMinimumPaneSize(20)

        #------------

        if wx.Platform == "__WXGTK__":
            self.dir = wx.GenericDirCtrl(splitter1, -1, dir='/home/', style=wx.DIRCTRL_DIR_ONLY)

        elif wx.Platform == "__WXMSW__":
            self.dir = wx.GenericDirCtrl(splitter1, -1, dir='C:/', style=wx.DIRCTRL_DIR_ONLY)

        #------------

        self.lc1 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)
        self.lc2 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)

        #------------

        dt = MyTextDropTarget(self.lc2)
        self.lc2.SetDropTarget(dt)

        #------------

        tree = self.dir.GetTreeCtrl()

        #------------

        splitter2.SplitHorizontally(self.lc1, self.lc2)
        splitter1.SplitVertically(self.dir, splitter2)

        #------------

        self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.OnDragInit, id=self.lc1.GetId())
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelect, id=tree.GetId())

        #------------

        self.OnSelect(0)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnSelect(self, event):
        list = os.listdir(self.dir.GetPath())
        print("List dir :", list)
        self.lc1.ClearAll()
        self.lc2.ClearAll()

        for i in range(len(list)):
            if list[i][0] != '.':
                self.lc1.InsertItem(0, list[i])


    def OnDragInit(self, event):
        text = self.lc1.GetItemText(event.GetIndex())
        tdo = wx.TextDataObject(text)
        tds = wx.DropSource(self.lc1)
        tds.SetData(tdo)
        tds.DoDragDrop(True)

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "Dragdrop.py")
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
{{attachment:dragdrop.png}}

'''Figure: dragdrop.py'''

One of the advantages of the GUI over the console is its intuitiveness. You can learn a GUI program easier than a console application. You often do not need a manual. On the other hand, some graphical operations are too complex. For example, deleting a file by dragging it and droping it to the trash basket is very intuitive and easy to understand, but actually most people just press the delete key. (shift + delete) It is more effective. In our next example we explore a graphical operation, that is very handy. In most GUI text editors, you can open a file by simply dragging it from the file manager and dropping it on the editor.

{{{#!python
#!/usr/bin/python

# filedrop.py

import wx

#---------------------------------------------------------------------------

class FileDrop(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)

        self.window = window

    #-----------------------------------------------------------------------

    def OnDropFiles(self, x, y, filenames):
        for name in filenames:
            try:
                file = open(name, 'r', encoding='utf-8')
                text = file.read()
                self.window.WriteText(text)
                file.close()
            except IOError as error:
                dlg = wx.MessageDialog(None, 'Error opening file\n' + str(error))
                dlg.ShowModal()
            except UnicodeDecodeError as error:
                dlg = wx.MessageDialog(None, 'Cannot open non ascii files\n' + str(error))
                dlg.ShowModal()

        return True

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,
                          wx.DefaultPosition, wx.Size(450, 400))

        self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
        dt = FileDrop(self.text)
        self.text.SetDropTarget(dt)

        self.Centre()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, '')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
== Plotting ==
Link : [[https://wiki.wxpython.org/How%20to%20use%20Plot%20-%20Part%203%20(Phoenix)|https://wiki.wxpython.org/How%20to%20use%20Plot%20-%20Part%203%20(Phoenix)]]

{{attachment:scattergraph.png}} {{attachment:linegraph.png}} {{attachment:bargraph.png}}

'''Figures: scatter, line, bar graphs'''

== Configuring application settings ==
Many applications allow users to configure their settings. Users can toggle tooltips on and of, change fonts, default download paths etc. Mostly they have a menu option called preferences. Application settings are saved to the hard disk, so that users do not have to change the settings each time the application starts.

In wxPython we have wx.Config class to do our job.

On Linux, settings are stored in a simple hidden file. This file is located in the home user directory by default.  The location of the configuration file can be changed. The name of the file is specified in the constructor of the wx.Config class.
||||<style="text-align:center;">'''Various wx.Config methods''' ||
||<#d0d0d0>{{{string Read(string key, string defaultVal='')}}} ||<#d0d0d0>return a string value of a key if it exists, defaultVal otherwise ||
||{{{int ReadInt(string key, int defaultVal=0)}}} ||return an integer value of the key if it exists, defaultVal otherwise ||
||<#d0d0d0>{{{float ReadFloat(string key, float defaultVal=0.0)}}} ||<#d0d0d0>return a float value of a key if it exists, defaultVal otherwise ||
||{{{bool ReadBool(string key, bool defaultVal=False)}}} ||return a boolean value of a key if it exists, defaultVal otherwise ||
||<#d0d0d0>{{{bool Write(string key, string value)}}} ||<#d0d0d0>write a string value, return True on success ||
||{{{bool WriteInt(string key, int value)}}} ||write an integer value, return True on success ||
||<#d0d0d0>{{{bool WriteFloat(string key, float value)}}} ||<#d0d0d0>write a float value, return True on success ||
||{{{bool WriteBool(string key, bool value)}}} ||write a boolean value, return True on success ||
||<#d0d0d0>{{{bool Exists(string value)}}} ||<#d0d0d0>return True if a key with a given name exists ||




In the following code example, we can cofigure the size of the window. If there is no configuration file, the height and the width of the window is set to the defaul 250 px value. We can set these values to a range from 200 - 500px. After we save our values and restart the application, the window size is set to our preffered values.

{{{#!python
#!/usr/bin/python

# myconfig.py

import wx

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):

        self.cfg = wx.Config('myconfig')

        if self.cfg.Exists('width'):
            w, h = self.cfg.ReadInt('width'), self.cfg.ReadInt('height')
        else:
            (w, h) = (250, 250)

        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(w, h))

        #------------

        wx.StaticText(self, -1, 'Width :', (20, 20))
        wx.StaticText(self, -1, 'Height :', (20, 70))

        self.sc1 = wx.SpinCtrl(self, -1, str(w), (80, 15), (60, -1), min=200, max=500)
        self.sc2 = wx.SpinCtrl(self, -1, str(h), (80, 65), (60, -1), min=200, max=500)

        wx.Button(self, 1, '&Save', (20, 120))

        #------------

        self.Bind(wx.EVT_BUTTON, self.OnSave, id=1)

        #------------

        self.statusbar = self.CreateStatusBar()

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnSave(self, event):
        self.cfg.WriteInt("width", self.sc1.GetValue())
        self.cfg.WriteInt("height", self.sc2.GetValue())
        self.statusbar.SetStatusText('Configuration saved, %s ' % wx.Now())

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Myconfig.py')
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
Here we have the contents of a configuration file to our code example . It consists of two key, value pairs.

{{{
$ cat .myconfig
height=220
width=340
}}}
{{attachment:myconfig.png}}

'''Figure: myconfig.py'''

== wxPython functions ==
wxPython provides several useful functions. We can implement them easily in our programs.  Technically, these functions are module functions. e.g defined in a module scope. They resemble what we know as static methods in C++ or Java.

=== System functions ===
||||<style="text-align:center;">'''System functions''' ||
||<#d0d0d0>{{{wx.Bell()}}} ||<#d0d0d0>beep a sound ||
||{{{wx.GetDisplaySize()}}} ||return the current display mode ||
||<#d0d0d0>{{{wx.GetEmailAddress()}}} ||<#d0d0d0>return user's email address ||
||{{{wx.GetFullHostName()}}} ||return full host name ||
||<#d0d0d0>{{{wx.GetHomeDir()}}} ||<#d0d0d0>return the user's home direstory ||
||{{{wx.GetOsVersion()}}} ||return Os version ||
||<#d0d0d0>{{{wx.GetOsDescription()}}} ||<#d0d0d0>return a full Os description ||
||{{{wx.GetFreeMemory()}}} ||not working ||
||<#d0d0d0>{{{wx.GetMousePosition()}}} ||<#d0d0d0>return mouse position ||
||{{{wx.GetProcessId()}}} ||return a process id of our application ||
||<#d0d0d0>{{{wx.GetUserName()}}} ||<#d0d0d0>returns a user's name ||
||{{{wx.GetUTCTime()}}} ||return number of seconds ||
||<#d0d0d0>{{{wx.Now()}}} ||<#d0d0d0>return current timestamp ||
||{{{wx.Shell(string command)}}} ||execute a command in a shell ||


=== Dialog functions ===
These functions create dialogs. They do some common tasks.
||||<style="text-align:center;">'''Dialog functions''' ||
||<#d0d0d0>{{{wx.GetTextFromUser()}}} ||<#d0d0d0>get a text from user ||
||{{{wx.DirSelector()}}} ||select a directory ||
||<#d0d0d0>{{{wx.FileSelector()}}} ||<#d0d0d0>select a file ||
||{{{wx.GetNumberFromUser()}}} ||get a long number from user ||
||<#d0d0d0>{{{wx.GetSingleChoice()}}} ||<#d0d0d0>something ||
||{{{wx.GetSingleChoiceIndex()}}} ||something ||
||<#d0d0d0>{{{wx.GetSingleChoiceIndex()}}} ||<#d0d0d0>something ||
||{{{wx.LoadFileSelector()}}} ||load a file ||
||<#d0d0d0>{{{wx.MessageBox()}}} ||<#d0d0d0>show a message dialog ||
||{{{wx.SaveFileSelector()}}} ||saves a file ||




{{{
string wx.GetTextFromUser(string message, string caption='', string default_value='', wx.Window parent=None)
string wx.DirSelector(string message=wx.DirSelectorPromptStr, string defaultPath='', style=wx.DD_DEFAULT_STYLE,
                      wx.Point pos=wx.DefaultPosition, wx.Window parent=None)
string wx.FileSelector(string message=wx.FileSelectorPromptStr, string default_path='', string default_filename='',
                       string default_extension='', string wildcard=wx.FileSelectorDefaultWildcardStr,
                       integer flags=0, wx.Window parent=None, integer x=-1, integer y=-1)
long wx.GetNumberFromUser(string message, string prompt, string caption, long value, long min=0, long max=100,
                          wx.Window parent=None, wx.Point pos=wx.DefaultPosition)
string wx.GetSingleChoice(string message, string caption, integer choices, string choices_array,
                          wx.Window parent=None, integer x=-1, integer y=-1, bool centre=True, integer width=150,
                          integer height=200)
integer wx.GetSingleChoiceIndex(string message, string caption, integer choices, string choices_array,
                                wx.Window parent=None, integer x=-1, integer y=-1, bool centre=True,
                                integer width=150, integer height=200)
string wx.LoadFileSelector(string what, string extension, string default_name='', wx.Window parent=None)
integer wx.MessageBox(string message, string caption='', style=wx.OK | wx.CENTRE, wx.Window parent=None,
                      integer x=-1, integer y=-1)
string wx.SaveFileSelector(string what, string extension, string default_name='', wx.Window parent=None)
}}}
=== Other functions ===
Here is a list of various other functions
||||<style="text-align:center;">'''Other functions''' ||
||<#d0d0d0>{{{wx.Exit()}}} ||<#d0d0d0>exit application ||
||{{{bool wx.Yield()}}} ||yield to other applications or messages ||
||<#d0d0d0>{{{bool wx.YieldIfNeeded()}}} ||<#d0d0d0>something ||
||{{{bool SafeYield(wx.Window window=None, bool onlyIfNeeded=False)}}} ||something ||
||<#d0d0d0>{{{wx.WakeUpIdle()}}} ||<#d0d0d0>empty the message queue ||
||{{{wx.PostEvent(wx.EvtHandler dest, wx.Event event)}}} ||{{{wx.EventHandler}}} to be processed later ||
||<#d0d0d0>{{{PyApp wx.GetApp()}}} ||<#d0d0d0>return a reference to the current wx.App object ||
||{{{wx.SetDefaultPyEncoding(string encoding)}}} ||set the current encoding for working with wx.String ||
||<#d0d0d0>{{{string wx.GetDefaultPyEncoding()}}} ||<#d0d0d0>get the current encoding for working with wx.String ||




== Using xml resource files ==
The idea behind xml resources is to separate the interface from the code of an application. Several GUI builders use this concept for creating interfaces. For example the famous Glade.

In our example we create a simple frame window with one button. We load resources from a file, load a panel and bind an event to a button.

{{{#!python
#!/usr/bin/python

# xml.py

import  wx
import  wx.xrc  as  xrc

#---------------------------------------------------------------------------

class Xml(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        res = xrc.XmlResource('resource.xrc')
        res.LoadPanel(self, 'MyPanel')

        self.Bind(wx.EVT_BUTTON, self.OnClose,  id=xrc.XRCID('CloseButton'))

        #------------

        self.Center()

        #------------

        self.Show(True)

    #-----------------------------------------------------------------------

    def OnClose(self, event):
        self.Close()

#---------------------------------------------------------------------------

app = wx.App()
Xml(None, -1, 'xml.py')
app.MainLoop()
}}}
This is resource file "resource.xrc". It is a xml file, where we define our widgets and their patterns. In this file, we use tags like<object></object>, <item></item> etc.

{{{
<?xml version="1.0" ?>
<resource>
  <object class="wxPanel" name="MyPanel">
   <object class="wxButton" name="CloseButton">
    <label>Close</label>
    <pos>150,100</pos>
   </object>
  </object>
</resource>
}}}
We use these two calls for working with widgets:

 * XRCID(resource_name) - gives us the id of a button or menu item
 * XRCCTRL(resource_name) - gives us the handlers of our widgets defined in resource file

== Skeletons ==
In this section, we will create some application skeletons. Our scripts will work out the interface but will not implement the functionality. The goal is to show, how several well known GUI interfaces could be done in wxPython. Most manuals, tutorials and books show only the basic usage of a widget. When I was a beginner, I always wondered how this or this could be done. And I think, many newbies think the same.

=== File Hunter ===
File Hunter is a skeleton of a file manager. It copies the lookout of the Krusader, the best file manager available on Unix systems.

{{{#!python
#!/usr/bin/python

# filemanager.py

"""
ZetCode wxPython tutorial

This program creates a skeleton
of a file manager UI.

author: Jan Bodnar
website: zetcode.com
last edited: May 2018
"""

import wx
import os
import time

ID_BUTTON=100
ID_EXIT=200
ID_SPLITTER=300

#---------------------------------------------------------------------------

class MyListCtrl(wx.ListCtrl):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, style=wx.LC_REPORT)

        images = ['images/empty.png', 'images/folder.png', 'images/source-py.png',
                  'images/image.png', 'images/pdf.png', 'images/up16.png']

        self.InsertColumn(0, 'Name')
        self.InsertColumn(1, 'Ext')
        self.InsertColumn(2, 'Size', wx.LIST_FORMAT_RIGHT)
        self.InsertColumn(3, 'Modified')

        self.SetColumnWidth(0, 120)
        self.SetColumnWidth(1, 35)
        self.SetColumnWidth(2, 60)
        self.SetColumnWidth(3, 420)

        self.il = wx.ImageList(16, 16)

        for i in images:

            self.il.Add(wx.Bitmap(i))

        self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)

        j = 1

        self.InsertItem(0, '..')
        self.SetItemImage(0, 5)

        #------------

        files = os.listdir('.')

        for i in files:
            (name, ext) = os.path.splitext(i)
            ex = ext[1:]
            size = os.path.getsize(i)
            sec = os.path.getmtime(i)

            self.InsertItem(j, name)
            self.SetItem(j, 1, ex)
            self.SetItem(j, 2, str(size) + ' B')
            self.SetItem(j, 3, time.strftime('%Y-%m-%d %H:%M', time.localtime(sec)))

            if os.path.isdir(i):
                self.SetItemImage(j, 1)
            elif ex == 'py':
                self.SetItemImage(j, 2)
            elif ex == 'jpg':
                self.SetItemImage(j, 3)
            elif ex == 'pdf':
                self.SetItemImage(j, 4)
            else:
                self.SetItemImage(j, 0)

            if (j % 2) == 0:

                self.SetItemBackgroundColour(j, '#e6f1f5')

            j = j + 1

#---------------------------------------------------------------------------

class Example(wx.Frame):
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    #-----------------------------------------------------------------------

    def InitUI(self):
        self.SetTitle("File Hunter")
        self.SetMinSize((760, 360))

        #------------

        self.splitter = wx.SplitterWindow(self, ID_SPLITTER, style=wx.SP_BORDER)
        self.splitter.SetMinimumPaneSize(50)

        p1 = MyListCtrl(self.splitter)
        p2 = MyListCtrl(self.splitter)

        self.splitter.SplitVertically(p1, p2)

        #------------

        filemenu= wx.Menu()
        filemenu.Append(ID_EXIT, "E&xit"," Terminate the program")
        editmenu = wx.Menu()
        netmenu = wx.Menu()
        showmenu = wx.Menu()
        configmenu = wx.Menu()
        helpmenu = wx.Menu()

        menuBar = wx.MenuBar()
        menuBar.Append(filemenu, "&File")
        menuBar.Append(editmenu, "&Edit")
        menuBar.Append(netmenu, "&Net")
        menuBar.Append(showmenu, "&Show")
        menuBar.Append(configmenu, "&Config")
        menuBar.Append(helpmenu, "&Help")
        self.SetMenuBar(menuBar)

        #------------

        tb = self.CreateToolBar( wx.TB_HORIZONTAL | wx.NO_BORDER |
                      wx.TB_FLAT)

        tb.AddTool(10, 'Previous', wx.Bitmap('images/previous.png'), shortHelp='Previous')
        tb.AddTool(20, 'Up', wx.Bitmap('images/up.png'), shortHelp='Up one directory')
        tb.AddTool(30, 'Home', wx.Bitmap('images/home.png'), shortHelp='Home')
        tb.AddTool(40, 'Refresh', wx.Bitmap('images/refresh.png'), shortHelp='Refresh')
        tb.AddSeparator()
        tb.AddTool(50, 'Edit text', wx.Bitmap('images/textedit.png'), shortHelp='Edit text')
        tb.AddTool(60, 'Terminal', wx.Bitmap('images/terminal.png'), shortHelp='Terminal')
        tb.AddSeparator()
        tb.AddTool(70, 'Help', wx.Bitmap('images/help.png'), shortHelp='Show help')
        tb.Realize()

        #------------

        button1 = wx.Button(self, ID_BUTTON + 1, "F3 View")
        button2 = wx.Button(self, ID_BUTTON + 2, "F4 Edit")
        button3 = wx.Button(self, ID_BUTTON + 3, "F5 Copy")
        button4 = wx.Button(self, ID_BUTTON + 4, "F6 Move")
        button5 = wx.Button(self, ID_BUTTON + 5, "F7 Mkdir")
        button6 = wx.Button(self, ID_BUTTON + 6, "F8 Delete")
        button7 = wx.Button(self, ID_BUTTON + 7, "F9 Rename")
        button8 = wx.Button(self, ID_EXIT, "F10 Quit")

        #------------

        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.sizer2.Add(button1, 1, wx.EXPAND)
        self.sizer2.Add(button2, 1, wx.EXPAND)
        self.sizer2.Add(button3, 1, wx.EXPAND)
        self.sizer2.Add(button4, 1, wx.EXPAND)
        self.sizer2.Add(button5, 1, wx.EXPAND)
        self.sizer2.Add(button6, 1, wx.EXPAND)
        self.sizer2.Add(button7, 1, wx.EXPAND)
        self.sizer2.Add(button8, 1, wx.EXPAND)

        self.sizer.Add(self.splitter,1,wx.EXPAND)
        self.sizer.Add(self.sizer2,0,wx.EXPAND)

        self.SetSizer(self.sizer)

        # size = wx.DisplaySize()
        # self.SetSize(size)

        #------------

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_SPLITTER_DCLICK, self.OnDoubleClick, id=ID_SPLITTER)
        self.Bind(wx.EVT_MENU, self.OnExit, id=ID_EXIT)
        self.Bind(wx.EVT_BUTTON, self.OnExit, id=ID_EXIT)

        #------------

        sb = self.CreateStatusBar()
        sb.SetStatusText(os.getcwd())

        #------------

        self.Center()


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


    def OnSize(self, event):
        size = self.GetSize()
        self.splitter.SetSashPosition(int(size.x / 2))

        event.Skip()


    def OnDoubleClick(self, event):
        size = self.GetSize()
        self.splitter.SetSashPosition(int(size.x / 2))

#---------------------------------------------------------------------------

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

#---------------------------------------------------------------------------

if __name__ == '__main__':
    main()
}}}
If you double click on the splitter widget, it will divide the File Hunter into two parts with the same width. The same happens, if you resize the main window.

{{attachment:filehunter.png}}

'''Figure: filemanager.py'''

=== SpreadSheet ===
Gnumeric, KSpread andOpenOffice Calc are famous spreadsheet applications available on Unix. The following example shows a skeleton of a spreadsheet application in wxPython.

{{{#!python
#!/usr/bin/python

# spreadsheet.py


"""
ZetCode wxPython tutorial

This program creates a SpreadSheet UI.

author: Jan Bodnar
website: zetcode.com
last edited: May 2018
"""

from wx.lib import sheet
import wx

#---------------------------------------------------------------------------

class MySheet(wx.grid.Grid):
    def __init__(self, *args, **kw):
        super(MySheet, self).__init__(*args, **kw)

        self.InitUI()

    #-----------------------------------------------------------------------

    def InitUI(self):
        nOfRows = 55
        nOfCols = 25

        self.row = self.col = 0
        self.CreateGrid(nOfRows, nOfCols)

        self.SetColLabelSize(20)
        self.SetRowLabelSize(50)

        self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnGridSelectCell)

        for i in range(nOfRows):
            self.SetRowSize(i, 20)

        for i in range(nOfCols):
            self.SetColSize(i, 75)


    def OnGridSelectCell(self, e):
        self.row, self.col = e.GetRow(), e.GetCol()

        control = self.GetParent().GetParent().position
        value =  self.GetColLabelValue(self.col) + self.GetRowLabelValue(self.row)
        control.SetValue(value)

        e.Skip()

#---------------------------------------------------------------------------

class Example(wx.Frame):
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    #-----------------------------------------------------------------------

    def InitUI(self):
        fonts = ['Times New Roman', 'Times', 'Courier', 'Courier New', 'Helvetica',
                'Sans', 'verdana', 'utkal', 'aakar', 'Arial']
        font_sizes = ['10', '11', '12', '14', '16']

        #------------

        menuBar = wx.MenuBar()

        menu1 = wx.Menu()
        menuBar.Append(menu1, '&File')
        menu2 = wx.Menu()
        menuBar.Append(menu2, '&Edit')
        menu3 = wx.Menu()
        menuBar.Append(menu3, '&Edit')
        menu4 = wx.Menu()
        menuBar.Append(menu4, '&Insert')
        menu5 = wx.Menu()
        menuBar.Append(menu5, 'F&ormat')
        menu6 = wx.Menu()
        menuBar.Append(menu6, '&Tools')
        menu7 = wx.Menu()
        menuBar.Append(menu7, '&Data')
        menu8 = wx.Menu()
        menuBar.Append(menu8, '&Help')

        self.SetMenuBar(menuBar)

        #------------

        toolbar1 = wx.ToolBar(self, style= wx.TB_HORIZONTAL)

        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/new.png'))
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/open.png'))
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/save.png'))

        toolbar1.AddSeparator()

        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/cut.png'))
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/copy.png'))
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/paste.png'))
        toolbar1.AddTool(wx.ID_ANY, '',  wx.Bitmap('images/delete.png'))

        toolbar1.AddSeparator()

        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/undo.png'))
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/redo.png'))

        toolbar1.AddSeparator()

        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/asc.png'))
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/desc.png'))

        toolbar1.AddSeparator()
        toolbar1.AddTool(wx.ID_ANY, '', wx.Bitmap('images/chart.png'))

        toolbar1.AddSeparator()
        toolbar1.AddTool(wx.ID_ANY, '',  wx.Bitmap('images/exit.png'))

        toolbar1.Realize()

        toolbar2 = wx.ToolBar(self, wx.TB_HORIZONTAL | wx.TB_TEXT)

        self.position = wx.TextCtrl(toolbar2)

        font = wx.ComboBox(toolbar2, value='Times', choices=fonts, size=(100, -1),
                style=wx.CB_DROPDOWN)

        font_height = wx.ComboBox(toolbar2, value='10', choices=font_sizes,
                size=(50, -1), style=wx.CB_DROPDOWN)

        toolbar2.AddControl(self.position)
        toolbar2.AddControl(font)
        toolbar2.AddControl(font_height)

        toolbar2.AddSeparator()

        toolbar2.AddCheckTool(wx.ID_ANY, '', wx.Bitmap('images/text-bold.png'))
        toolbar2.AddCheckTool(wx.ID_ANY, '', wx.Bitmap('images/text-italic.png'))
        toolbar2.AddCheckTool(wx.ID_ANY, '', wx.Bitmap('images/text-underline.png'))

        toolbar2.AddSeparator()

        toolbar2.AddTool(wx.ID_ANY, '', wx.Bitmap('images/align-left.png'))
        toolbar2.AddTool(wx.ID_ANY, '', wx.Bitmap('images/align-center.png'))
        toolbar2.AddTool(wx.ID_ANY, '', wx.Bitmap('images/align-right.png'))

        toolbar2.Realize()

        #------------

        notebook = wx.Notebook(self, style=wx.RIGHT)

        sheet1 = MySheet(notebook)
        sheet2 = MySheet(notebook)
        sheet3 = MySheet(notebook)
        sheet1.SetFocus()

        notebook.AddPage(sheet1, 'Sheet1')
        notebook.AddPage(sheet2, 'Sheet2')
        notebook.AddPage(sheet3, 'Sheet3')

        #------------

        box = wx.BoxSizer(wx.VERTICAL)

        box.Add(toolbar1, border=5)
        box.Add((5,5) , 0)
        box.Add(toolbar2)
        box.Add((5,10) , 0)
        box.Add(notebook, 1, wx.EXPAND)

        self.SetSizer(box)

        #------------

        self.CreateStatusBar()

        #------------

        self.SetSize((550, 550))
        self.SetTitle("SpreadSheet")

        #------------

        self.Centre()

#---------------------------------------------------------------------------

def main():

    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

#---------------------------------------------------------------------------

if __name__ == '__main__':
    main()
}}}
{{attachment:spreadsheet.png}}

'''Figure: spreadsheet.py'''

== Tips And Tricks ==
In this section we will show some tips in wxPython.

=== PopupMenu ===
The following code was committed by Chris Barker on the wxPython-users mailing list. Popup menu is here implemented in a separate class. This way, you don't have to manually check, if the events were already bound.

{{{#!python
#!/usr/bin/env python

# popup.py

import wx

app = wx.App()

#---------------------------------------------------------------------------

class MyPopupMenu(wx.Menu):
    def __init__(self, WinName):
        wx.Menu.__init__(self)

        self.WinName = WinName

        #------------

        item1 = wx.MenuItem(self, -1, "Item One")
        self.Append(item1)

        item2 = wx.MenuItem(self, -1,"Item Two")
        self.Append(item2)

        item3 = wx.MenuItem(self, -1,"Item Three")
        self.Append(item3)

        #------------

        self.Bind(wx.EVT_MENU, self.OnItem1, item1)
        self.Bind(wx.EVT_MENU, self.OnItem2, item2)
        self.Bind(wx.EVT_MENU, self.OnItem3, item3)

    #-----------------------------------------------------------------------

    def OnItem1(self, event):
        print("Item One selected in the %s window" % self.WinName)


    def OnItem2(self, event):
        print("Item Two selected in the %s window" % self.WinName)


    def OnItem3(self, event):
        print("Item Three selected in the %s window" % self.WinName)

#---------------------------------------------------------------------------

class MyWindow(wx.Window):
    def __init__(self, parent, color):
        wx.Window.__init__(self, parent, -1)

        self.color = color

        self.SetBackgroundColour(color)

        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)

    #-----------------------------------------------------------------------

    def OnRightDown(self,event):
        self.PopupMenu(MyPopupMenu(self.color), event.GetPosition())

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None, -1, "Popup.py", size=(300, 200))

        sizer = wx.GridSizer(2,2,5,5)
        sizer.Add(MyWindow(self,"blue"),1,wx.GROW)
        sizer.Add(MyWindow(self,"yellow"),1,wx.GROW)
        sizer.Add(MyWindow(self,"red"),1,wx.GROW)
        sizer.Add(MyWindow(self,"green"),1,wx.GROW)
        self.SetSizer(sizer)

        self.Show()

#---------------------------------------------------------------------------

frame = MyFrame()
app.SetTopWindow(frame)
app.MainLoop()
}}}
The example is just a single frame. This frame is divided into four windows.  If you right click on the frame, context menu pops up. Context menu consists of three commands. If you select any of them a message is sent to the console. It will say what item you selected plus the color of the window where you clicked with the mouse. This example shows the power of  the object oriented programming. Imagine you would have to do it the other way, by calculating manually the position of the pointer!

Notice that the popup menu is implemented as a new class.  This is a more elegant way of using popup menus as the following one, taken from the Demo application.

{{{
 def OnRightClick(self, event):
        # only do this part the first time so the events are only bound once
        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.popupID2 = wx.NewId()
            self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
        menu = wx.Menu()
        menu.Append(self.popupID1, "One")
        menu.Append(self.popupID2, "Two")
        self.PopupMenu(menu, event.GetPosition())
        menu.Destroy()
    def OnPopupOne(self, event):
        pass
    def OnPopupTwo(self, event):
        pass
}}}
There is one subtle thing in the code that needs some clarification. You only boud an  event once. It resides in event table afterwards. If it is done in the constructor, everything is ok.  But when you bound an event to a method in a method, you do it everytime when the method gets invoked. That's why we wrote a condition to ensure, we don't implement this overhead.

{{{
 if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.popupID2 = wx.NewId()
            self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
}}}
=== The tiniest wxPython application ===
Feel free to contact me, if you can shorthen it. Even for one single character.

{{{#!python
#!/usr/bin/python

# tiniestapp.py

import wx

#---------------------------------------------------------------------------

app = wx.App()

wx.Frame(None).Show()

app.MainLoop()
}}}
=== One-liner wxPython application ===
This is functionally equivalent to the tiniest wxPython application given above.

{{{#!python
#!/usr/bin/python

# onelinerapp.py

from wx import App, Frame

#---------------------------------------------------------------------------

type('', (App, object), {'OnInit': lambda self: Frame(None).Show()})().MainLoop()
}}}
=== Interactive Button ===
This tip shows how to program an interactive Button. This button reacts to users actions. In our case, the button changes its background colour. When you enter the area of the button widget with a mouse pointer,

{{{EVT_ENTER_WINDOW}}} event is generated. Simirarly, {{{EVT_LEAVE_WINDOW}}} event is generated, when you leave the area of the widget. So all you have to do is to bind those events to functions, that will change the colour/shape of the button widget appropriately.

{{{#!python
#!/usr/bin/python

# interactivebutton.py

import wx
import wx.lib.buttons  as  buttons

#---------------------------------------------------------------------------

class MyPanel(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, -1, wx.DefaultPosition)

        # Plain old text button based off GenButton().
        self.btn = buttons.GenButton(self, -1, "Button",
                                     pos=wx.Point(125, 100),
                                     size=(-1, -1))
        self.btn.SetFont(wx.Font(10, wx.FONTFAMILY_SWISS,
                                 wx.FONTSTYLE_NORMAL,
                                 wx.FONTWEIGHT_BOLD, False))
        self.btn.SetBezelWidth(1)
        self.btn.SetBackgroundColour(wx.LIGHT_GREY)
        self.btn.SetForegroundColour(wx.BLACK)
        self.btn.SetToolTip("This is a GenButton...")

        #------------

        self.btn.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterButton)
        self.btn.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveButton)

    #-----------------------------------------------------------------------

    def OnEnterButton(self, event):
        self.btn.SetBackgroundColour(wx.Colour(128, 128, 128))
        self.btn.Refresh()


    def OnLeaveButton(self, event):
        self.btn.SetBackgroundColour(wx.Colour(212, 208, 200))
        self.btn.Refresh()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = wx.Frame(None, -1, "Interactivebutton.py",
                         wx.DefaultPosition, wx.Size(350, 300))
        mypanel = MyPanel(frame, -1)
        frame.Centre()
        frame.Show(True)
        self.SetTopWindow(frame)

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
I have used{{{wx.GenButton}}} instead of basic {{{wx.Button}}}. {{{wx.GenButton}}} enables to change border settigs, which I find attractive. But {{{wx.Button}}} would work as well.

=== Error handling without dialogs ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20an%20alternative%20error%20messages%20(Phoenix)|https://wiki.wxpython.org/How%20to%20create%20an%20alternative%20error%20messages%20(Phoenix)]]

{{attachment:isabelle.png}}

'''Figure: isabelle.py'''

=== UndoRedoFramework ===
Many applications have the ability to undo and redo the user's actions. The following example shows how it can be accomplished in wxPython.

{{{#!python
#!/usr/bin/python

# undoredo.py

"""
ZetCode wxPython tutorial

In this example, we create two horizontal
toolbars.

author: Jan Bodnar
website: www.zetcode.com
last modified: April 2018
"""

import wx

#---------------------------------------------------------------------------

class Example(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)

        self.InitUI()

    #-----------------------------------------------------------------------

    def InitUI(self):

        self.count = 5

        #------------

        self.toolbar = self.CreateToolBar()
        tundo = self.toolbar.AddTool(wx.ID_UNDO, '', wx.Bitmap('tundo.png'))
        tredo = self.toolbar.AddTool(wx.ID_REDO, '', wx.Bitmap('tredo.png'))
        self.toolbar.EnableTool(wx.ID_REDO, False)
        self.toolbar.AddSeparator()
        texit = self.toolbar.AddTool(wx.ID_EXIT, '', wx.Bitmap('texit.png'))
        self.toolbar.Realize()

        #------------

        self.Bind(wx.EVT_TOOL, self.OnQuit, texit)
        self.Bind(wx.EVT_TOOL, self.OnUndo, tundo)
        self.Bind(wx.EVT_TOOL, self.OnRedo, tredo)

        #------------

        self.SetSize((350, 250))
        self.SetTitle('Undoredo.py')

        #------------

        self.Centre()


    def OnUndo(self, event):
        if self.count > 1 and self.count <= 5:
            self.count = self.count - 1

        if self.count == 1:
            self.toolbar.EnableTool(wx.ID_UNDO, False)

        if self.count == 4:
            self.toolbar.EnableTool(wx.ID_REDO, True)


    def OnRedo(self, event):
        if self.count < 5 and self.count >= 1:
            self.count = self.count + 1

        if self.count == 5:
            self.toolbar.EnableTool(wx.ID_REDO, False)

        if self.count == 2:
            self.toolbar.EnableTool(wx.ID_UNDO, True)


    def OnQuit(self, event):
        self.Close()

#---------------------------------------------------------------------------

def main():
    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

#---------------------------------------------------------------------------

if __name__ == '__main__':
    main()
}}}
In our example, we want to undo and redo cell text changes and column and row size changes. So we must bind relevant events to our methods. These bindings are not visible in our sample code. You can find them in sheet.py file, in CSheet class:

{{{
self.Bind(wx.grid.EVT_GRID_ROW_SIZE, self.OnRowSize)
self.Bind(wx.grid.EVT_GRID_COL_SIZE, self.OnColSize)
self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnCellChange)
}}}
In these three methods we create Undo objects. These objects are{{{UndoText}}}, {{{UndoColSize}}} and {{{UndoRowSize}}}. Each object has two methods. {{{undo()}}} and {{{redo()}}}. They are responsible for bringing to the state of the application before the change was done and vice versa. The objects are then appended to stockUndo list. This way we ensure, that all necessary changes are stored. Finally, when we press undo, redo buttons, we call {{{OnUndo()}}} and {{{OnRedo()}}} methods. The following method calls actually do the job:

{{{
a.undo()
a.redo()
}}}
The objects move between stockUndo and stockRedo lists accordingly. Also when there are no objects left, we disable a button with the{{{EnableTool()}}} method.

{{attachment:newt.png}}

'''Figure: newt.py'''

== Gripts ==
In this section we will show some small, complete scripts. These graphical scripts or "gripts" will demonstrate various areas in programming.  Programming in Python, wxPython is easier than in most other toolkits. But it is still a laborious task. There is a long, long way from easy scripts to professional applications.

=== Tom ===
Each application should have a good name. Short and easily remembered. So, we have Tom. A simple gript that  sends an email.

{{{#!python
#!/usr/bin/python

# Tom.py

import wx
import smtplib

#---------------------------------------------------------------------------

class Tom(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title,
                           wx.DefaultPosition, wx.Size(400, 420))

        panel = wx.Panel(self, -1)

        st1 = wx.StaticText(panel, -1, 'From : ')
        st2 = wx.StaticText(panel, -1, 'To : ')
        st3 = wx.StaticText(panel, -1, 'Subject : ')
        self.tc1 = wx.TextCtrl(panel, -1, size=(180, -1))
        self.tc2 = wx.TextCtrl(panel, -1, size=(180, -1))
        self.tc3 = wx.TextCtrl(panel, -1, size=(180, -1))
        self.write = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
        button_send = wx.Button(panel, 1, '&Send')

        #------------

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)

        hbox1.Add(st1, 0, wx.LEFT, 10)
        hbox1.Add(self.tc1, 0, wx.LEFT, 20)

        hbox2.Add(st2, 0, wx.LEFT, 10)
        hbox2.Add(self.tc2, 0, wx.LEFT, 35)

        hbox3.Add(st3, 0, wx.LEFT, 10)
        hbox3.Add(self.tc3, 0, wx.LEFT, 9)

        vbox.Add(hbox1, 0, wx.TOP, 10)
        vbox.Add(hbox2, 0, wx.TOP, 10)
        vbox.Add(hbox3, 0, wx.TOP, 10)
        vbox.Add(self.write, 1, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, 15)
        vbox.Add(button_send, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 20)

        panel.SetSizer(vbox)

        #------------

        self.Bind(wx.EVT_BUTTON, self.OnSend, id=1)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnSend(self, event):
        sender = self.tc1.GetValue()
        recipient = self.tc2.GetValue()
        subject = self.tc3.GetValue()
        text = self.write.GetValue()
        header = 'From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n' % (sender, recipient, subject)
        message = header + text

        try:
            server = smtplib.SMTP('mail.chello.sk')
            server.sendmail(sender, recipient, message)
            server.quit()
            dlg = wx.MessageDialog(self, 'Email was successfully sent',
                                   'Success', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()

        except smtplib.SMTPException as error:
            dlg = wx.MessageDialog(self, 'Failed to send email',
                                   'Error', wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = Tom(None, -1, 'Tom.py')
        frame.ShowModal()
        frame.Destroy()

        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
For working with emails we need to import smtp module.

{{{
import smtplib
}}}
From, To and Subject options must be separated by carriedge return and newline as shown here. This weird thing is requested by RFC 821 norm. So we must follow it.

{{{
header = 'From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n' % (sender, recipient, subject)
}}}
Next we create an SMTP connection. Here you specify your settings. Each ISP gives you the name of the  pop and smtp servers. In my case, 'mail.chello.sk' is a name for both.  A mail is sent by calling the sendmail() method. Finally, we quit the connection with the quit() method.

{{{
server = smtplib.SMTP('mail.chello.sk')
server.sendmail(sender, recipient, message)
server.quit()
}}}
{{attachment:tom.png}}

'''Figure: tom.py'''

=== Editor ===
Link : [[https://wiki.wxpython.org/How%20to%20create%20a%20simple%20text%20editor%20(Phoenix)#Sample_three|https://wiki.wxpython.org/How%20to%20create%20a%20simple%20text%20editor%20(Phoenix)#Sample_three]]

{{attachment:editor.png}}

'''Figure: editor.py'''

=== Kika ===
Kika is a gript that connects to an ftp site. If a login is successfull, Kika shows a connected icon on the statusbar. Otherwise, a disconnected icon is displayed.  We use an ftplib module from the python standard library.  If you do not have an ftp account, you can try to login to some anonymous ftp sites.

{{{#!python
#!/usr/bin/python

# kika.py

from ftplib import FTP, all_errors
import wx

#---------------------------------------------------------------------------

class MyStatusBar(wx.StatusBar):
    def __init__(self, parent):
        wx.StatusBar.__init__(self, parent)

        self.SetFieldsCount(2)
        self.SetStatusText('Welcome to Kika', 0)
        self.SetStatusWidths([-5, -2])

        #------------

        self.icon = wx.StaticBitmap(self, -1, wx.Bitmap('icons/disconnected.png'))

        #------------

        self.Bind(wx.EVT_SIZE, self.OnSize)

        #------------

        self.PlaceIcon()

    #-----------------------------------------------------------------------

    def PlaceIcon(self):
        rect = self.GetFieldRect(1)
        self.icon.SetPosition((rect.x+3, rect.y+3))


    def OnSize(self, event):
        self.PlaceIcon()

#---------------------------------------------------------------------------

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(270, 270))

        self.ftp = None

        #------------

        self.SetMinSize((270, 270))

        #------------

        wx.StaticText(self, -1, 'Ftp site', (10, 20))
        wx.StaticText(self, -1, 'Login', (10, 60))
        wx.StaticText(self, -1, 'Password', (10, 100))

        self.ftpsite = wx.TextCtrl(self, -1, '',  (110, 15), (120, -1))
        self.login = wx.TextCtrl(self, -1, '',  (110, 55), (120, -1))
        self.password = wx.TextCtrl(self, -1, '',  (110, 95), (120, -1), style=wx.TE_PASSWORD)

        con = wx.Button(self, 1, 'Connect', (10, 160))
        discon = wx.Button(self, 2, 'DisConnect', (120, 160))

        #------------

        self.Bind(wx.EVT_BUTTON, self.OnConnect, id=1)
        self.Bind(wx.EVT_BUTTON, self.OnDisConnect, id=2)

        #------------

        self.statusbar = MyStatusBar(self)
        self.SetStatusBar(self.statusbar)

        #------------

        self.Centre()

    #-----------------------------------------------------------------------

    def OnConnect(self, event):
        if not self.ftp:
            ftpsite = self.ftpsite.GetValue()
            login = self.login.GetValue()
            password = self.password.GetValue()

            try:
                self.ftp = FTP(ftpsite)
                var = self.ftp.login(login, password)
                self.statusbar.SetStatusText('User connected')
                self.statusbar.icon.SetBitmap(wx.Bitmap('icons/connected.png'))

            except AttributeError:
                self.statusbar.SetForegroundColour(wx.RED)
                self.statusbar.SetStatusText('Incorrect params')
                self.ftp = None

            except all_errors as err:
                self.statusbar.SetStatusText(str(err))
                self.ftp = None


    def OnDisConnect(self, event):
        if self.ftp:
            self.ftp.quit()
            self.ftp = None
            self.statusbar.SetStatusText('User disconnected')
            self.statusbar.icon.SetBitmap(wx.Bitmap('icons/disconnected.png'))

#---------------------------------------------------------------------------

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Kika.py')
        frame.Show(True)
        return True

#---------------------------------------------------------------------------

app = MyApp(0)
app.MainLoop()
}}}
Notice that each time the window is resized, we must position our icon to a new place.

{{{
def PlaceIcon(self):
    rect = self.GetFieldRect(1)
    self.icon.SetPosition((rect.x+3, rect.y+3))
}}}
{{attachment:kika.png}}

'''Figure: kika.py'''

== Appendix ==
=== Cursor IDs ===
||wx.CURSOR_ARROW ||wx.CURSOR_RIGHT_ARROW ||wx.CURSOR_BLANK ||
||wx.CURSOR_BULLSEYE ||wx.CURSOR_CHAR ||wx.CURSOR_CROSS ||
||wx.CURSOR_HAND ||wx.CURSOR_IBEAM ||wx.CURSOR_LEFT_BUTTON ||
||wx.CURSOR_MAGNIFIER ||wx.CURSOR_MIDDLE_BUTTON ||wx.CURSOR_NO_ENTRY ||
||wx.CURSOR_PAINT_BRUSH ||wx.CURSOR_PENCIL ||wx.CURSOR_POINT_LEFT ||
||wx.CURSOR_POINT_RIGHT ||wx.CURSOR_QUESTION_ARROW ||wx.CURSOR_RIGHT_BUTTON ||
||wx.CURSOR_SIZENESW ||wx.CURSOR_SIZENS ||wx.CURSOR_SIZENWSE ||
||wx.CURSOR_SIZEWE ||wx.CURSOR_SIZING ||wx.CURSOR_SPRAYCAN ||
||wx.CURSOR_WAIT ||wx.CURSOR_WATCH ||wx.CURSOR_ARROWWAIT ||


=== wx.Frame styles ===
||wx.DEFAULT_FRAME_STYLE ||wx.ICONIZE ||wx.FRAME_SHAPED ||
||wx.CAPTION ||wx.MINIMIZE ||wx.MINIMIZE_BOX ||
||wx.MAXIMIZE ||wx.MAXIMIZE_BOX ||wx.STAY_ON_TOP ||
||wx.SYSTEM_MENU ||wx.SIMPLE_BORDER ||wx.RESIZE_BORDER ||
||wx.FRAME_TOOL_WINDOW ||wx.FRAME_NO_TASKBAR ||wx.FRAME_FLOAT_ON_PARENT ||
||wx.FRAME_EX_CONTEXTHELP || || ||


=== Standard Colour Database ===
||AQUAMARINE ||BLACK ||BLUE ||BLUE VIOLET ||BROWN ||CADET BLUE ||CORAL ||
||CORNFLOWER BLUE ||CYAN ||DARK GREY ||DARK GREEN ||DARK OLIVE GREEN ||DARK ORCHID ||DARK SLATE BLUE ||
||DARK SLATE GREY ||DARK TURQUOISE ||DIM GREY ||FIREBRICK ||FOREST GREEN ||GOLD ||GOLDENROD ||
||GREY ||GREEN ||GREEN YELLOW ||INDIAN RED ||KHAKI ||LIGHT BLUE ||LIGHT GREY ||
||LIGHT STEEL BLUE ||LIME GREEN ||MAGENTA ||MAROON ||MEDIUM AQUAMARINE ||MEDIUM BLUE ||MEDIUM FOREST GREEN ||
||MEDIUM GOLDENROD ||MEDIUM ORCHID ||MEDIUM SEA GREEN ||MEDIUM SLATE BLUE ||MEDIUM SPRING GREEN ||MEDIUM TURQUOISE ||MEDIUM VIOLET RED ||
||MIDNIGHT BLUE ||NAVY ||ORANGE ||ORANGE RED ||ORCHID ||PALE GREEN ||PINK ||
||PLUM ||PURPLE ||RED ||SALMON ||SEA GREEN ||SIENNA ||SKY BLUE ||
||SLATE BLUE ||SPRING GREEN ||STEEL BLUE ||TAN ||THISTLE ||TURQUOISE ||VIOLET ||
||VIOLET RED ||WHEAT ||WHITE ||YELLOW ||YELLOW GREEN ||


=== wx.Pen styles ===
||wx.SOLID ||wx.TRANSPARENT ||wx.DOT ||wx.LONG_DASH ||wx.SHORT_DASH ||
||wx.DOT_DASH ||wx.STIPPLE ||wx.USER_DASH ||wx.BDIAGONAL_HATCH ||wx.CROSSDIAG_HATCH ||
||wx.FDIAGONAL_HATCH ||wx.CROSS_HATCH ||wx.HORIZONTAL_HATCH ||wx.VERTICAL_HATCH ||


=== wx.Brush styles ===
||wx.BLUE_BRUSH ||wx.GREEN_BRUSH ||wx.WHITE_BRUSH ||
||wx.BLACK_BRUSH ||wx.GREY_BRUSH ||wx.MEDIUM_GREY_BRUSH ||
||wx.LIGHT_GREY_BRUSH ||wx.TRANSPARENT_BRUSH ||wx.CYAN_BRUSH ||
||wx.RED_BRUSH ||


=== CalendarCtrl styles ===
||CAL_SUNDAY_FIRST ||CAL_MONDAY_FIRST ||CAL_SHOW_HOLIDAYS ||CAL_NO_YEAR_CHANGE ||
||CAL_NO_MONTH_CHANGE ||CAL_SEQUENTIAL_MONTH_SELECTION ||CAL_SHOW_SURROUNDING_WEEKS ||CAL_HITTEST_NOWHERE ||
||CAL_HITTEST_HEADER ||CAL_HITTEST_DAY ||CAL_HITTEST_INCMONTH ||||<style="text-align:center;">CAL_HITTEST_DECMONTH ||
||CAL_HITTEST_SURROUNDING_WEEK ||CAL_BORDER_NONE ||CAL_BORDER_SQUARE ||CAL_BORDER_ROUND ||


=== Keycodes ===
||WXK_BACK ||WXK_TAB ||WXK_RETURN ||WXK_ESCAPE ||WXK_SPACE ||
||WXK_DELETE ||WXK_START ||WXK_LBUTTON ||WXK_RBUTTON ||WXK_CANCEL ||
||WXK_MBUTTON ||WXK_CLEAR ||WXK_SHIFT ||WXK_CONTROL ||WXK_MENU ||
||WXK_PAUSE ||WXK_CAPITAL ||WXK_PRIOR ||WXK_NEXT ||WXK_END ||
||WXK_HOME ||WXK_LEFT ||WXK_UP ||WXK_RIGHT ||WXK_DOWN ||
||WXK_SELECT ||WXK_PRINT ||WXK_EXECUTE ||WXK_SNAPSHOT ||WXK_INSERT ||
||WXK_HELP ||WXK_NUMPAD0 ||WXK_NUMPAD1 ||WXK_NUMPAD2 ||WXK_NUMPAD3 ||
||WXK_NUMPAD4 ||WXK_NUMPAD5 ||WXK_NUMPAD6 ||WXK_NUMPAD7 ||WXK_NUMPAD8 ||
||WXK_NUMPAD9 ||WXK_MULTIPLY ||WXK_ADD ||WXK_SEPARATOR ||WXK_SUBTRACT ||
||WXK_DECIMAL ||WXK_DIVIDE ||WXK_F1 ||WXK_F2 ||WXK_F3 ||
||WXK_F4 ||WXK_F5 ||WXK_F6 ||WXK_F7 ||WXK_F8 ||
||WXK_F9 ||WXK_F10 ||WXK_F11 ||WXK_F12 ||WXK_F13 ||
||WXK_F14 ||WXK_F15 ||WXK_F16 ||WXK_F17 ||WXK_F18 ||
||WXK_F19 ||WXK_F20 ||WXK_F21 ||WXK_F22 ||WXK_F23 ||
||WXK_F24 ||WXK_NUMLOCK ||WXK_SCROLL ||WXK_PAGEUP ||WXK_PAGEDOWN ||
||WXK_NUMPAD_SPACE ||WXK_NUMPAD_TAB ||WXK_NUMPAD_ENTER ||WXK_NUMPAD_F1 ||WXK_NUMPAD_F2 ||
||WXK_NUMPAD_F3 ||WXK_NUMPAD_F4 ||WXK_NUMPAD_HOME ||WXK_NUMPAD_LEFT ||WXK_NUMPAD_UP ||
||WXK_NUMPAD_RIGHT ||WXK_NUMPAD_DOWN ||WXK_NUMPAD_PRIOR ||WXK_NUMPAD_PAGEUP ||WXK_NUMPAD_NEXT ||
||WXK_NUMPAD_PAGEDOWN ||WXK_NUMPAD_END ||WXK_NUMPAD_BEGIN ||WXK_NUMPAD_INSERT ||WXK_NUMPAD_DELETE ||
||WXK_NUMPAD_EQUAL ||WXK_NUMPAD_MULTIPLY ||WXK_NUMPAD_ADD ||WXK_NUMPAD_SEPARATOR ||
||WXK_NUMPAD_SUBTRACT || ||WXK_NUMPAD_DECIMAL ||WXK_NUMPAD_DIVIDE ||


== Comments... ==
Date (d/m/y) Person (bot) Comments :

??/04/05 - Jan Bodnar / ZetCode (Created page for wxPython).

??/??/?? - Adil  Hasan (I've added a little example extending the {{{wx.TreeCtrl}}} example to create a  window with a  tree and moveable splitter window at AnotherTutorialTreeCtrlComment).

03/11/20 - Ecco (Updated examples for wxPython Phoenix (only scripts)).