Starting wxPython (GUI code)

Reply

Join Date: Oct 2004
Posts: 3,941
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 911
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Starting wxPython (GUI code)

 
1
  #1
Jun 9th, 2008
The idea of this thread is to help the beginning wxPython GUI programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
5
  #2
Jun 9th, 2008
Well, here's the tutorial like you asked for. I've expanded on it quite a bit. Could people please read over it, in case I've made mistakes? There's a better version at my blog because it features screenshots. Link: http://fuse.baywords.com/wxpython-tutorial/

Tutorial: GUI programming with wxPython

Index
Introduction
Start
Sizers
Putting it in classes
Event handling
Binding the enter key
Creating dropdown menus
Message and file browsing dialogues
Appendix

Introduction
Hi there! So you've made a few scripts in Python. They work really well, you maybe know your way around file IO, string manipulation, and list splicing (and heck maybe even regular expressions and other cool stuff)... but you're thinking "Is that it? Surely there's more to Python." So this is it: GUI programming. Here I explain how to make the move from the command line to full-blown graphical programmes like you see in KDE, Mac or Windows.

GUI programming is fast, self-contained, and simple. So you can code your functions first, or your GUI first - it's up to you. GUI programming is like LEGO: you have a few core blocks and you build everything else from those blocks. There's not much you can't build, and once you understand how those few core blocks work, where they fit, GUI programming will become second nature. There are numerous GUI packages available to use with Python. Tkinter comes with Python, whilst Qt and GTK are used to programme KDE and Gnome for linux, respectively. Which do I suggest you use? wxPython. It's not used by Gnome, KDE, or Windows, but it is, in my opinion, the most 'Pythonic' GUI package. It's powerful and efficient. It also inherits the native look, so you don't need to worry about it not 'fitting in' or looking correct.

To start with, download wxPython here: http://www.wxpython.org/download.php

Windows, Linux/UNIX, and Mac are supported. You might like to note the words of Guido van Rossum, creator of Python:
"wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first."

Once you've installed that, load up IDLE or your IDE of choice, and create a new script:

Start

  1. import wx
  2. # always add this line, or your code won't compile - the wx module contains the GUI code you'll use
  3.  
  4. """The start of our wxPython GUI tutorial"""
  5.  
  6. app = wx.App(redirect=False) # create a wx application
  7.  
  8. window = wx.Frame(None, title = 'Sample GUI App') # create a window
  9. btn = wx.Button(window)
  10. # create a button 'widget' on the window - note how the button receives the window. This creates a tree-like structure where the window is the parent node and anything else like buttons are child nodes.
  11.  
  12. window.Show() # make the frame (and hence button) visible
  13. app.MainLoop() # keep things going

Moderator's note: Some programming editors don't like the extra long comment lines, so run the above code without them ...
  1. import wx
  2.  
  3. """The start of our wxPython GUI tutorial"""
  4.  
  5. app = wx.App(redirect=False)
  6.  
  7. window = wx.Frame(None, title = 'Sample GUI App')
  8. btn = wx.Button(window)
  9.  
  10. window.Show()
  11. app.MainLoop()

This makes a window. It then puts a button on the window. Yes, the button takes up the whole window. Have a read, understand it, fiddle if you can, then go on. Please compile this code now to confirm it runs.

Note the bit 'redirect=False'. This is so that errors go to the interpreter instead of pop up in their own window. You may want to turn this back to True (or just delete it) later on, but for now you'll likely be encountering errors that crash the programme and require you to kill it to exit - so you want a record of the error. To kill the programme when you've made an error, right-click it in the taskbar, then select close, wait a bit, then press 'End Task' at the prompt. If this isn't working, press ctrl+alt+delete, go to processes and kill pythonw.exe (make sure it's the one that's about 23mb, not the 7mb ones, which are where you're typing your code). Onwards:

  1. import wx
  2.  
  3. """Example with custom sizes and positions for widgets and frames."""
  4.  
  5. app = wx.App(redirect=False)
  6. window = wx.Frame(None, title = 'Sample GUI App',
  7. pos = (100,100), size = (400,500))
  8.  
  9. helloBtn = wx.Button(window, label = 'Hello',
  10. pos = (400 - 60 - 15, 10), size = (60,25))
  11. byeBtn = wx.Button(window, label = 'Bye',
  12. pos = (400 - 120 - 15, 10), size = (60,25))
  13. printArea = wx.TextCtrl(window,
  14. pos = (10, 10), size = (400 - 120 - 15 - 10, 25),
  15. style = wx.TE_READONLY)
  16.  
  17. window.Show()
  18. app.MainLoop()

Compile and run this code first. Now look at the placement of widgets and what they are. Notice wx.TextCtrl is a text box. It's quite flexible - allowing multiline text with scroll bars, read only mode, write mode, etc. I've set it to read only for what I am about to do with it. You modify many features of a 'widget' by changing or adding things to the 'style' parameter, as above.

Also look at the position and size parameters. Fiddle with them a bit - they move and change the size of the widget. Compile and run, etc. Press the buttons. Note how they do nothing? That's because we need 'event handlers'.

Before I go on to event handlers, I'd like to make this GUI more flexible. For example, press the maximise button (top right). Notice how the programme doesn't expand to fit the screen? Let's fix that. It's fairly simple. Just add an extra 'node' in the tree; put a layer between the window frame and the widgets. It's called a 'sizer':
Last edited by vegaseat; Jun 21st, 2009 at 9:54 am. Reason: added a note
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #3
Jun 9th, 2008
Sizers

  1. import wx
  2.  
  3. """Example with sizers for dynamic resizing."""
  4.  
  5. app = wx.App(redirect=False)
  6.  
  7. window = wx.Frame(None, title = 'Sample GUI App',
  8. pos = (100,100), size = (400,500))
  9. background = wx.Panel(window)
  10.  
  11. loadBtn = wx.Button(background, label = 'Load')
  12. transferBtn = wx.Button(background, label = 'Transfer')
  13. inputArea = wx.TextCtrl(background)
  14. transferArea = wx.TextCtrl(background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  15.  
  16. horizontalBox = wx.BoxSizer()
  17. horizontalBox.Add(inputArea, proportion = 1, border = 0)
  18. horizontalBox.Add(transferBtn, proportion = 0, border = 0)
  19. horizontalBox.Add(loadBtn, proportion = 0, border = 0)
  20.  
  21. verticalBox = wx.BoxSizer(wx.VERTICAL)
  22. verticalBox.Add(horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
  23. verticalBox.Add(transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  24.  
  25. background.SetSizer(verticalBox)
  26. window.Show()
  27. app.MainLoop()

Notice how the 'tree' is preserved? You can eventually trace the buttons and text box back to the parent window through the background widget.

Remember, anything starting with a lower case letter tends to be an arbitrary variable name which you can rename to whatever you want. It is the things with capitals at the start that are important. Conventionally (at least in C++, Java and Haskell), you name variables and functions: thisIsAVariable, and classes: ThisIsAClass. So you could rename 'window' and 'background' to anything you wanted. Same applies to the widget names.

Have a fiddle with that. Sizers are a bit complex at first but you should use them instead of statically defining the size and start co-ords. Note the hierarchy: horizontalBox is a child of verticalBox. Position in the programme depends on location in the code, as you'll see below.

Note I changed the button and textbox names and added a new textbox. Examine the 'style' parameters. One is for input, one is for output. The output box is also multiline - like word wrap. Because the output box isn't for typing in, it was given the read-only style. Note how to combine two styles we used something called "bit-wise OR"? You may know it as a single pipe: |

Resize the window and confirm it works.

Oh, and the wx.VERTICAL value indicates the sizer is vertical. Otherwise the default is horizontal. Proportion=0 means make the widget as small as possible. If a widget had proportion = 1 and another had proportion = 2, then the first widget would take up 1/3 of the space (1+2 = 3) whilst the second would take up 2/3, after the proportion = 0 widgets had been considered.

Now, I want you to try and add TWO more widgets to the application. Add two buttons above inputArea. These two buttons need to be side-by-side, like the load and transfer buttons.

Did it work? Or did you accidentally add them above each-other, like this:

Screenshot: http://img149.imageshack.us/img149/6...glayoutvq5.png

To fully describe the location of a widget in the frame, you need to have one vertical box sizer, and as many horizontal box sizers as you have rows with more than one widget. So if you're adding a row of widgets that are side-by-side, you'll need a new horizontal box sizer:

  1. import wx
  2.  
  3. """Example with a 2D grid of sizers of sorts for more complex widget placement."""
  4.  
  5. app = wx.App(redirect=False)
  6.  
  7. window = wx.Frame(None, title = 'Sample GUI App',
  8. pos = (100,100), size = (400,500))
  9. background = wx.Panel(window)
  10.  
  11. loadBtn = wx.Button(background, label = 'Load')
  12. transferBtn = wx.Button(background, label = 'Transfer')
  13. inputArea = wx.TextCtrl(background)
  14. transferArea = wx.TextCtrl(background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  15.  
  16. exOneBtn = wx.Button(background, label = 'example one')
  17. exTwoBtn = wx.Button(background, label = 'example two')
  18.  
  19. horizontalBoxOne = wx.BoxSizer()
  20. horizontalBoxOne.Add(exOneBtn, proportion = 1, border = 0)
  21. horizontalBoxOne.Add(exTwoBtn, proportion = 1, border = 0)
  22.  
  23. horizontalBoxTwo = wx.BoxSizer()
  24. horizontalBoxTwo.Add(inputArea, proportion = 1, border = 0)
  25. horizontalBoxTwo.Add(transferBtn, proportion = 0, border = 0)
  26. horizontalBoxTwo.Add(loadBtn, proportion = 0, border = 0)
  27.  
  28. verticalBox = wx.BoxSizer(wx.VERTICAL)
  29. verticalBox.Add(horizontalBoxOne, proportion = 0, flag = wx.EXPAND, border = 0)
  30. verticalBox.Add(horizontalBoxTwo, proportion = 0, flag = wx.EXPAND, border = 0)
  31. verticalBox.Add(transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  32.  
  33. background.SetSizer(verticalBox)
  34. window.Show()
  35. app.MainLoop()

Screenshot: http://img237.imageshack.us/img237/2...tlayoutuq4.png
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #4
Jun 9th, 2008
Putting it in classes

One more thing before event handling... let's make our code more shall we say 'standard':

  1. import wx
  2.  
  3. # Declare constants in capitals and as global variables at the start of your code
  4. # This makes it much easier to change them later, especially if they are used often.
  5. # It also indicates they are values that won't change throughout the programme's execution.
  6.  
  7. WINDOW_WIDTH = 400
  8. WINDOW_HEIGHT = 500
  9.  
  10. class MainFrame(wx.Frame):
  11.  
  12. def __init__(self):
  13. wx.Frame.__init__(self, None, title = 'Sample GUI App',
  14. pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
  15.  
  16. self.background = wx.Panel(self)
  17.  
  18. self.loadBtn = wx.Button(self.background, label = 'Load')
  19. self.transferBtn = wx.Button(self.background, label = 'Transfer')
  20. self.inputArea = wx.TextCtrl(self.background)
  21. self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  22.  
  23. self.horizontalBox = wx.BoxSizer()
  24. self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
  25. self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
  26. self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)
  27.  
  28. self.verticalBox = wx.BoxSizer(wx.VERTICAL)
  29. self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
  30. self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  31.  
  32. self.background.SetSizer(self.verticalBox)
  33. self.Show()
  34.  
  35. app = wx.App(redirect=False)
  36. window = MainFrame()
  37. app.MainLoop()

I have thrown it all in a class. That's about it. Look over it, compile it, run it, understand it, etc. Note how you can always use classes to seperate parts of your programme. Generally whenever you have a new panel/frame/window, you should put it in its own class. Now on to the good stuff.
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #5
Jun 9th, 2008
Event handling

  1. import wx
  2.  
  3. WINDOW_WIDTH = 400
  4. WINDOW_HEIGHT = 500
  5.  
  6. class MainFrame(wx.Frame):
  7. """A working programme! Event handling, binding, methods, the lot."""
  8. def __init__(self):
  9. wx.Frame.__init__(self, None, title = 'Sample GUI App',
  10. pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
  11.  
  12. self.background = wx.Panel(self)
  13.  
  14. self.loadBtn = wx.Button(self.background, label = 'Load')
  15. self.loadBtn.Bind(wx.EVT_BUTTON, self.loadEvent)
  16.  
  17. self.transferBtn = wx.Button(self.background, label = 'Transfer')
  18. self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
  19.  
  20. self.inputArea = wx.TextCtrl(self.background)
  21. self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  22.  
  23. self.horizontalBox = wx.BoxSizer()
  24. self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
  25. self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
  26. self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)
  27.  
  28. self.verticalBox = wx.BoxSizer(wx.VERTICAL)
  29. self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
  30. self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  31.  
  32. self.background.SetSizer(self.verticalBox)
  33. self.Show()
  34.  
  35. def loadEvent(self, event):
  36. fileContents = open(self.inputArea.GetValue(), 'rb')
  37. self.transferArea.SetValue(fileContents.read())
  38. fileContents.close()
  39.  
  40. def transferEvent(self, event):
  41. self.transferArea.SetValue(self.inputArea.GetValue())
  42.  
  43. app = wx.App(redirect=False)
  44. window = MainFrame()
  45. app.MainLoop()

I added two bind commands, one for each button, and two methods to the class. That's it. Have fun fiddling with your own methods!

(The programme transfer whatever you type into the small box, inputArea, into the larger box, transferArea once you press 'Transfer'. Alternatively, you can type a file location into the inputArea and press load and it will load that file into the transferArea.)

Binding the enter key

Maybe you'd like to know how to make a textbox call a certain method when somebody hits the enter key? Add the style wx.TE_PROCESS_ENTER to the textbox's style section, then add a new binding below the textbox: textboxWidget.Bind(wx.EVT_TEXT_ENTER, functionNameHere), like so:

  1. import wx
  2.  
  3. WINDOW_WIDTH = 400
  4. WINDOW_HEIGHT = 500
  5.  
  6. class MainFrame(wx.Frame):
  7. """Now we've added an event handler for somebody hitting the enter key."""
  8. def __init__(self):
  9. wx.Frame.__init__(self, None, title = 'Sample GUI App',
  10. pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
  11.  
  12. self.background = wx.Panel(self)
  13.  
  14. self.loadBtn = wx.Button(self.background, label = 'Load')
  15. self.loadBtn.Bind(wx.EVT_BUTTON, self.loadEvent)
  16.  
  17. self.transferBtn = wx.Button(self.background, label = 'Transfer')
  18. self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
  19.  
  20. self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
  21. self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
  22.  
  23. self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  24.  
  25. self.horizontalBox = wx.BoxSizer()
  26. self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
  27. self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
  28. self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)
  29.  
  30. self.verticalBox = wx.BoxSizer(wx.VERTICAL)
  31. self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
  32. self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  33.  
  34. self.background.SetSizer(self.verticalBox)
  35. self.Show()
  36.  
  37. def loadEvent(self, event):
  38. fileContents = open(self.inputArea.GetValue(), 'rb')
  39. self.transferArea.SetValue(fileContents.read())
  40. fileContents.close()
  41.  
  42. def transferEvent(self, event):
  43. self.transferArea.SetValue(self.inputArea.GetValue())
  44.  
  45. app = wx.App(redirect=False)
  46. window = MainFrame()
  47. app.MainLoop()

Whenever you type something into the top textbox, then hit enter, it transfers it to the bottom one - just like if you'd hit the 'Transfer' button.
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #6
Jun 9th, 2008
Creating dropdown menus

  1. import wx
  2.  
  3. WINDOW_WIDTH = 400
  4. WINDOW_HEIGHT = 500
  5.  
  6. class MainFrame(wx.Frame):
  7. """We've finally added menubars."""
  8. def __init__(self):
  9. wx.Frame.__init__(self, None, title = 'Sample GUI App',
  10. pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
  11.  
  12. # Menubar.
  13. self.menuBar = wx.MenuBar()
  14. self.menuFile = wx.Menu() # Create a dropdown menu for 'File'
  15. self.menuInfo = wx.Menu() # Create a dropdown menu for 'Info'
  16. self.SetMenuBar(self.menuBar) # Tell the main frame what menubar to use.
  17.  
  18. self.menuBar.Append(self.menuFile, '&File') # Add a menu.
  19.  
  20. self.loadItem = self.menuFile.Append(-1, '&Load') # Add an item to the menu.
  21. self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)
  22. # Bind an event to the menu item. Note how for menu items the Bind format is different?
  23. # I specify the widget to be bound as the last parameter, not just before 'Bind', as I usually do.
  24. # You can use this version for any binding you do, if you want. It's necessary for menus, though.
  25.  
  26. self.exitItem = self.menuFile.Append(-1, 'E&xit')
  27. self.Bind(wx.EVT_MENU, self.exitEvent, self.exitItem)
  28.  
  29. self.menuBar.Append(self.menuInfo, '&Info')
  30. # Add another menu. Note how their order on the menubar depends on the order they appear in your code?
  31.  
  32. self.aboutItem = self.menuInfo.Append(-1, '&About')
  33. self.Bind(wx.EVT_MENU, self.aboutEvent, self.aboutItem)
  34.  
  35. self.helpItem = self.menuInfo.Append(-1, '&Help')
  36. self.Bind(wx.EVT_MENU, self.helpEvent, self.helpItem)
  37.  
  38. # Start of sizers and widgets contained within.
  39. self.background = wx.Panel(self)
  40.  
  41. self.transferBtn = wx.Button(self.background, label = 'Transfer')
  42. self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
  43.  
  44. self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
  45. self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
  46.  
  47. self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  48.  
  49. self.horizontalBox = wx.BoxSizer()
  50. self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
  51. self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
  52.  
  53. self.verticalBox = wx.BoxSizer(wx.VERTICAL)
  54. self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
  55. self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  56.  
  57. self.background.SetSizer(self.verticalBox)
  58. self.Show()
  59.  
  60. def loadEvent(self, event):
  61. print "placeholder"
  62.  
  63. def exitEvent(self, event):
  64. print "placeholder"
  65.  
  66. def helpEvent(self, event):
  67. print "placeholder"
  68.  
  69. def aboutEvent(self, event):
  70. print "placeholder"
  71.  
  72. def transferEvent(self, event):
  73. self.transferArea.SetValue(self.inputArea.GetValue())
  74.  
  75. app = wx.App(redirect=False)
  76. window = MainFrame()
  77. app.MainLoop()

Now, the 'Load' button is gone, and I've added a menu bar with 2 menus each with 2 menu items. Each menu item does something, but it's only to print 'placeholder'. Let's give them a real purpose:
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #7
Jun 9th, 2008
Message and file browsing dialogues

The widgets we need are wx.FileDialog and wx.MessageDialog. Now, because we only want it when we go to 'File' -> 'Load' on the menubar, we will actually create it in the 'Load' event method. Similarly, I will expand the event methods of 'Exit', 'Help', and 'About'.

  1. import wx
  2. import os
  3.  
  4. WINDOW_WIDTH = 400
  5. WINDOW_HEIGHT = 500
  6.  
  7. class MainFrame(wx.Frame):
  8. """We've finally added menubars."""
  9. def __init__(self):
  10. wx.Frame.__init__(self, None, title = 'Sample GUI App',
  11. pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
  12.  
  13. # Menubar.
  14. self.menuBar = wx.MenuBar()
  15. self.SetMenuBar(self.menuBar)
  16. self.menuFile = wx.Menu()
  17. self.menuInfo = wx.Menu()
  18.  
  19. self.menuBar.Append(self.menuFile, '&File')
  20.  
  21. self.loadItem = self.menuFile.Append(-1, '&Load')
  22. self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)
  23.  
  24. self.exitItem = self.menuFile.Append(-1, 'E&xit')
  25. self.Bind(wx.EVT_MENU, self.exitEvent, self.exitItem)
  26.  
  27. self.menuBar.Append(self.menuInfo, '&Info')
  28.  
  29. self.aboutItem = self.menuInfo.Append(-1, '&About')
  30. self.Bind(wx.EVT_MENU, self.aboutEvent, self.aboutItem)
  31.  
  32. self.helpItem = self.menuInfo.Append(-1, '&Help')
  33. self.Bind(wx.EVT_MENU, self.helpEvent, self.helpItem)
  34.  
  35. # Start of sizers and widgets contained within.
  36. self.background = wx.Panel(self)
  37.  
  38. self.transferBtn = wx.Button(self.background, label = 'Transfer')
  39. self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
  40.  
  41. self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
  42. self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
  43.  
  44. self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)
  45.  
  46. self.horizontalBox = wx.BoxSizer()
  47. self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
  48. self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
  49.  
  50. self.verticalBox = wx.BoxSizer(wx.VERTICAL)
  51. self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
  52. self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)
  53.  
  54. self.background.SetSizer(self.verticalBox)
  55. self.Show()
  56.  
  57. def loadEvent(self, event):
  58. """Create a load dialogue box, load a file onto transferArea, then destroy the load box."""
  59. loadBox = wx.FileDialog(self, message="Open",
  60. defaultDir=os.getcwd(), defaultFile="", style=wx.OPEN)
  61. if loadBox.ShowModal() == wx.ID_OK: # When the user clicks 'Open', do this:
  62. fileName = loadBox.GetPath()
  63. target = open(fileName, 'rb')
  64. self.transferArea.SetValue(target.read())
  65. target.close()
  66. loadBox.Destroy()
  67. # Note how I destroy the load box now so I can return to the programme.
  68.  
  69. def exitEvent(self, event):
  70. """Exit programme."""
  71. self.Destroy()
  72.  
  73. def helpEvent(self, event):
  74. """Writes help information to the transferArea."""
  75. self.transferArea.SetValue("""You could type a help file for the user here.""")
  76.  
  77. def aboutEvent(self, event):
  78. """Pops up a little message box that tells you stuff."""
  79. aboutInfo = """Hello there!
  80. I am a person, and I coded this programme."""
  81. aboutBox = wx.MessageDialog(self, message=aboutInfo, caption='About',
  82. style = wx.ICON_INFORMATION | wx.STAY_ON_TOP | wx.OK)
  83. if aboutBox.ShowModal() == wx.ID_OK: # Until the user clicks OK, show the message
  84. aboutBox.Destroy()
  85.  
  86. def transferEvent(self, event):
  87. """Moves data in inputArea onto transferArea."""
  88. self.transferArea.SetValue(self.inputArea.GetValue())
  89.  
  90. app = wx.App(redirect=False)
  91. window = MainFrame()
  92. app.MainLoop()

Note how I imported the module os, aswell. Also notice how the 'Exit' item in the menubar now closes the programme (the X still closes it, too).

The end result: http://img291.imageshack.us/img291/7...althingwy1.png
Last edited by Fuse; Jun 9th, 2008 at 6:11 am.
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #8
Jun 9th, 2008
The end result: http://img291.imageshack.us/img291/7...althingwy1.png

If you have any further inquiries, do a google search, read a few forum threads, and read the documentation for the method or class in question. Feel free to ask me (and others) here, too, but try and make it a last resort - you learn more through trial and error, generally.

Also, if you have any corrections, tips, or suggestions for this tutorial, please leave a comment in this thread, or on my blog: http://fuse.baywords.com/wxpython-tutorial/

Appendix

Widgets
wx.TextCtrl(parent, style=?)
Standard GUI textbox.
Styles:
wx.TE_PROCESS_ENTER
-- When the user hits the enter key, a method is called. The method called depends on the binding, as in Binding the enter key above.

wx.TE_MULTILINE
-- Textbox spans multiple lines, starting a new line when the sentence would otherwise go off-screen. Has a vertical scrollbar by default.

wx.HSCROLL
-- Create a horizontal scrollbar. I believe this works for some other widgets (hence no 'TE' prefix), but haven't tested it.

wx.TE_READONLY
-- Textbox cannot be typed in, but may still be written to by calling widgetName.SetValue(valueHere)

The are more. If you know what they are, please post them in this thread so that a moderator can update this section! I can't find them in the API... no surprise there.

wx.Button(parent, label='?')
Standard GUI button.
Styles: ?

wx.SearchCtrl(parent, style=?)
This class inherits wx.TextCtrl, so generally all the stuff (e.g. styles) you can do with that applies here.
This widget can have a dropdown menu added to it. There is a semi-decent explanation here: http://www.wxpython.org/docs/api/wx....trl-class.html
I personally use this class for the SetDescriptiveText("text here") method that allows you to display greyed out text which dissapears when the user clicks and types in the box. You can turn off the left-hand side search icon, too.
Extra styles: ?

wx.MenuBar and wx.Menu
The manu bar at the top left-hand side of almost all programmes in almost all OS'es
Sample use:
# Create menubar
self.menuBar = wx.MenuBar()
# Set it as the programme's menubar
self.SetMenuBar(self.menuBar)
# Create a menu
self.menuFile = wx.Menu()
# Add the menu to the menubar
self.menuBar.Append(self.menuFile, '&File')
# Create and add an item to the menu
self.loadItem = self.menuFile.Append(-1, '&Load')
# Give the item an event handler
self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)

wx.MessageDialog
Used for errors, warnings, about, etc.
Styles here: http://www.wxpython.org/docs/api/wx....log-class.html

Events
wx.EVT_TEXT_ENTER
wx.EVT_BUTTON
wx.EVT_MENU

There are many more here: http://www.wxpython.org/docs/api/wx.Event-class.html
I believe they are all listed, but navigating to find the event you want is very much a guessing game.

References
Style guide: http://wiki.wxpython.org/wxPython%20Style%20Guide
-- It would be wise to read that style guide. It was written in 2006, so it is relatively up to date, and offers good advice on style to use for your more advanced GUI programming.

vegasat's binding example:
http://www.daniweb.com/forums/post335474-3.html
-- How to place widgets in a class, how to do event handling.

wxPython standard documentation:
http://www.wxpython.org/docs/api/wx-module.html
-- Don't rely on it for anything useful. There's a reason I wrote this guide.

General Python style guide:
http://www.python.org/dev/peps/pep-0008/
-- How you should probably format your code.

http://fuse.baywords.com/wxpython-tutorial/
Last edited by Fuse; Jun 9th, 2008 at 6:11 am.
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 46
Reputation: Fuse is an unknown quantity at this point 
Solved Threads: 3
Fuse's Avatar
Fuse Fuse is offline Offline
Light Poster

Re: Starting wxPython (GUI code)

 
1
  #9
Jun 9th, 2008
Source code for final programme and hard copy of tutorial:
http://www.mediafire.com/?fwdynnltynj

Also, you might be interested in making an executable version of your programme in Windows. I suggest you use py2exe: http://www.py2exe.org/

The executable produced is minuscule in size, but the catch is that needs like half the Python libraries as well as the full wx library to run. So most programmes you make will be at about the 15mb mark. They can easily be compressed to less than half that size, however using 7-zip, rar or zip for example.

py2exe seems to produce application that have more of a Windows 95/98/ME feel rather than an XP feel, I've found. I'm not sure if I'm missing libraries or what, but at the end of the day, it runs perfectly and looks native enough, so. But if anybody knows how to keep the XP theme it has in IDLE, let me know.
Mir's Fuselage

Because what's not to like about being killed by a toilet seat from Mir's atmospheric re-entry?
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting wxPython (GUI code)

 
2
  #10
Jun 9th, 2008
Here is a templet file that allows you to package your wxPython program to an executable file with the py2exe module. It contains an XML manifest that gives the wxPython widgets a Windows XP appearance on XP machines:
  1. # Py2Exe version 6.6 setup file for wxPython GUI programs.
  2. # Creates a single executable file.
  3. #
  4. # Simply change the filename entry to whatever you called your source file.
  5. # Optionally edit the version info and add the name of your icon file.
  6. # It's easiest to save the modified templet code for instance as
  7. # wx2exe.py to the same folder that containes your source file
  8. # and the optional iconfile like "icon.ico"
  9. #
  10. # Now run the customized wx2exe.py ...
  11. #
  12. # Two subfolders will be created called build and dist.
  13. # The dist folder contains your .exe file, MSVCR71.dll and w9xpopen.exe
  14. # w9xpopen.exe is needed for os.popen() only.
  15. # Your .exe file contains your byte code, all needed modules
  16. # and the Python interpreter.
  17. # The MSVCR71.dll can be distributed, but is often already in
  18. # the Windows system32 folder.
  19. # The build folder is for info only and can be deleted.
  20.  
  21.  
  22. from distutils.core import setup
  23. import py2exe
  24. import sys
  25.  
  26. # Enter the filename of your wxPython source code file to compile.
  27. # Your distribution file will be this filename with a .exe extension.
  28. filename = "wxButton1.py"
  29.  
  30. # this creates the filename of your .exe file in the dist folder
  31. if filename.endswith(".py"):
  32. distribution = filename[:-3]
  33. elif filename.endswith(".pyw"):
  34. distribution = filename[:-4]
  35.  
  36. # if run without args, build executables in quiet mode
  37. if len(sys.argv) == 1:
  38. sys.argv.append("py2exe")
  39. sys.argv.append("-q")
  40.  
  41. class Target:
  42. def __init__(self, **kw):
  43. self.__dict__.update(kw)
  44. # for the versioninfo resources, edit to your needs
  45. self.version = "0.6.6"
  46. self.company_name = "My Company"
  47. self.copyright = "no copyright"
  48. # fill this in with your own program description
  49. self.name = "WxPython Button Test"
  50.  
  51. # start of manifest for custom icon and appearance ...
  52. #
  53. # This XML manifest will be inserted as resource into your .exe file
  54. # It gives the controls a Windows XP appearance (if run on XP)
  55. #
  56. manifest_template = '''
  57. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  58. <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  59. <assemblyIdentity
  60. version="5.0.0.0"
  61. processorArchitecture="x86"
  62. name="%(prog)s"
  63. type="win32"
  64. />
  65. <description>%(prog)s Program</description>
  66. <dependency>
  67. <dependentAssembly>
  68. <assemblyIdentity
  69. type="win32"
  70. name="Microsoft.Windows.Common-Controls"
  71. version="6.0.0.0"
  72. processorArchitecture="X86"
  73. publicKeyToken="6595b64144ccf1df"
  74. language="*"
  75. />
  76. </dependentAssembly>
  77. </dependency>
  78. </assembly>
  79. '''
  80.  
  81. RT_MANIFEST = 24
  82.  
  83. # description is the versioninfo resource
  84. # script is the wxPython code file
  85. # manifest_template is the above XML code
  86. # distribution will be the exe filename
  87. # icon_resource is optional, remove any comment and give it
  88. # an iconfile you have, otherwise a default icon is used
  89. # dest_base will be the exe filename
  90. test_wx = Target(
  91. description = "A GUI app",
  92. script = filename,
  93. other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog=distribution))],
  94. #icon_resources = [(1, "icon.ico")],
  95. dest_base = distribution)
  96.  
  97. # end of manifest
  98.  
  99. setup(
  100. options = {"py2exe": {"compressed": 1,
  101. "optimize": 2,
  102. "ascii": 1,
  103. "bundle_files": 1}},
  104. zipfile = None,
  105. windows = [test_wx]
  106. )
Any questions? Ask in a separate thread in the Python forum please.
Last edited by Ene Uran; Jun 9th, 2008 at 12:22 pm.
drink her pretty
Reply With Quote Quick reply to this message  
Reply

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC