Fuse 17 Light Poster

paulthom had an idea of adding help text to a texbox when the programme loads. The help text just explains what to type in the box and needs to disappear once the user types anything or clicks in the box. If you're interested in doing similar, or want to know how to use mouse events, go here:

http://www.daniweb.com/forums/thread128788.html

Aside from being example code that shows you how to implement such a feature, it demonstrates how funny things happen if you don't return focus to the calling widget by typing event.Skip() at the end of the mouse event's handler method.

The wxPython documentation on mouse events is a decent reference: http://www.wxpython.org/docs/api/wx.MouseEvent-class.html

Fuse 17 Light Poster

Maybe os.system and lpr?

Fuse 17 Light Poster

Phew! I thought you were going to say they don't compile. Cheers. :D

Fuse 17 Light Poster

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.

Fuse 17 Light Poster

The end result: http://img291.imageshack.us/img291/711/finalthingwy1.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 …

Fuse 17 Light Poster

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'.

import wx
import os

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):
    """We've finally added menubars."""
    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))

        # Menubar.  
        self.menuBar = wx.MenuBar()
        self.SetMenuBar(self.menuBar)
        self.menuFile = wx.Menu()
        self.menuInfo = wx.Menu()

        self.menuBar.Append(self.menuFile, '&File')

        self.loadItem = self.menuFile.Append(-1, '&Load')
        self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)
       
        self.exitItem = self.menuFile.Append(-1, 'E&xit')
        self.Bind(wx.EVT_MENU, self.exitEvent, self.exitItem)
        
        self.menuBar.Append(self.menuInfo, '&Info')
        
        self.aboutItem = self.menuInfo.Append(-1, '&About')
        self.Bind(wx.EVT_MENU, self.aboutEvent, self.aboutItem)
        
        self.helpItem = self.menuInfo.Append(-1, '&Help')
        self.Bind(wx.EVT_MENU, self.helpEvent, self.helpItem)

        # Start of sizers and widgets contained within.
        self.background = wx.Panel(self)
      
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
        
        self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
        self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
        
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
        self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

        self.background.SetSizer(self.verticalBox)
        self.Show()

    def loadEvent(self, event):
        """Create a load dialogue box, load a file onto transferArea, then destroy the load box."""
        loadBox = wx.FileDialog(self, message="Open",
                                defaultDir=os.getcwd(), defaultFile="", style=wx.OPEN)
        if loadBox.ShowModal() == wx.ID_OK: # When the user clicks 'Open', do this:
            fileName = loadBox.GetPath()
            target = open(fileName, 'rb')
            self.transferArea.SetValue(target.read())
            target.close() …
Fuse 17 Light Poster

Creating dropdown menus

import wx

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):
    """We've finally added menubars."""
    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))

        # Menubar.  
        self.menuBar = wx.MenuBar()
        self.menuFile = wx.Menu() # Create a dropdown menu for 'File'
        self.menuInfo = wx.Menu() # Create a dropdown menu for 'Info'
        self.SetMenuBar(self.menuBar) # Tell the main frame what menubar to use.

        self.menuBar.Append(self.menuFile, '&File') # Add a menu.
        
        self.loadItem = self.menuFile.Append(-1, '&Load') # Add an item to the menu.
        self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)
        # Bind an event to the menu item. Note how for menu items the Bind format is different?
        # I specify the widget to be bound as the last parameter, not just before 'Bind', as I usually do.
        # You can use this version for any binding you do, if you want. It's necessary for menus, though.
       
        self.exitItem = self.menuFile.Append(-1, 'E&xit')
        self.Bind(wx.EVT_MENU, self.exitEvent, self.exitItem)
        
        self.menuBar.Append(self.menuInfo, '&Info')
        # Add another menu. Note how their order on the menubar depends on the order they appear in your code?
        
        self.aboutItem = self.menuInfo.Append(-1, '&About')
        self.Bind(wx.EVT_MENU, self.aboutEvent, self.aboutItem)
        
        self.helpItem = self.menuInfo.Append(-1, '&Help')
        self.Bind(wx.EVT_MENU, self.helpEvent, self.helpItem)

        # Start of sizers and widgets contained within.
        self.background = wx.Panel(self)
        
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
        
        self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
        self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
        
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border …
Fuse 17 Light Poster

Event handling

import wx

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):
    """A working programme! Event handling, binding, methods, the lot."""
    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
        
        self.background = wx.Panel(self)

        self.loadBtn = wx.Button(self.background, label = 'Load')
        self.loadBtn.Bind(wx.EVT_BUTTON, self.loadEvent)
        
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
        
        self.inputArea = wx.TextCtrl(self.background)
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
        self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
        self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

        self.background.SetSizer(self.verticalBox)
        self.Show()

    def loadEvent(self, event):
        fileContents = open(self.inputArea.GetValue(), 'rb')
        self.transferArea.SetValue(fileContents.read())
        fileContents.close()

    def transferEvent(self, event):
        self.transferArea.SetValue(self.inputArea.GetValue())
    
app = wx.App(redirect=False)
window = MainFrame()
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 …

Fuse 17 Light Poster

Putting it in classes

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

import wx

# Declare constants in capitals and as global variables at the start of your code
# This makes it much easier to change them later, especially if they are used often.
# It also indicates they are values that won't change throughout the programme's execution.

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
        
        self.background = wx.Panel(self)

        self.loadBtn = wx.Button(self.background, label = 'Load')
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.inputArea = wx.TextCtrl(self.background)
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
        self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
        self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

        self.background.SetSizer(self.verticalBox)
        self.Show()
    
app = wx.App(redirect=False)
window = MainFrame()
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.

Fuse 17 Light Poster

Sizers

import wx

"""Example with sizers for dynamic resizing."""

app = wx.App(redirect=False)

window = wx.Frame(None, title = 'Sample GUI App',
                  pos = (100,100), size = (400,500))
background = wx.Panel(window)

loadBtn = wx.Button(background, label = 'Load')
transferBtn = wx.Button(background, label = 'Transfer')
inputArea = wx.TextCtrl(background)
transferArea = wx.TextCtrl(background, style = wx.TE_READONLY | wx.TE_MULTILINE)

horizontalBox = wx.BoxSizer()
horizontalBox.Add(inputArea, proportion = 1, border = 0)
horizontalBox.Add(transferBtn, proportion = 0, border = 0)
horizontalBox.Add(loadBtn, proportion = 0, border = 0)

verticalBox = wx.BoxSizer(wx.VERTICAL)
verticalBox.Add(horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
verticalBox.Add(transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

background.SetSizer(verticalBox)
window.Show()
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 …

TranquilWaters commented: This starting guide in wxPython is great :-) +0
Fuse 17 Light Poster

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 …

lllllIllIlllI commented: Really really good tutorial +1
Lardmeister commented: nicely done, easy to understand +4
sneekula commented: You make wxPython sound very interesting +4
Fuse 17 Light Poster

I think so, too. Up to vegasat.

Fuse 17 Light Poster

The best way to learn is to teach a subject. I have enjoyed your presentation of wxPython too.

Compared to Tkinter, wxPython's power is in its clever widgets, a more pythonic approach.

I hear you! And I'm not sure what this mysterious 'Pythonic' coding style is, but I suspect it is generally how I intuitively code, due to my first programming experiences being Java's pure OO paradigm and Haskell's pure functional paradigm.

As a side note, I highly recommend Haskell to everybody (especially anybody who enjoys Python). There's even a wxHaskell implementation, which mainly uses monads to emulate imperative programming. Not the best language to code in, but an invaluable language to learn to improve your programming ability and style. As a bonus, Haskell is white-space sensitive like Python, and has a beautiful standard library (better than or equal to Python's in my opinion), so it is understandably easy to learn once you adjust to the functional paradigm.

In fact I have a feeling Python was influenced by Haskell or something similar, because it has white-space sensitivity, list comprehensions, lambda functions, lists, tuples, strict typing, an interpreter, etc. I learnt from an excellent book: 'Haskell: The Craft of Functional Programming', if anyone's interested. In fact, I'd probably describe Python as Haskell + Java.

Fuse 17 Light Poster

Sure thing! Glad you liked it.

I'll clean it up tomorrow (or soonish) as there are a few errors and typos, as well as elaborate on some points (such as using multiple horizontal box sizers for more complex widget positioning). I'm also teaching myself about some other widgets, so I'll add them if I feel they could do with explaining.

Fuse 17 Light Poster

I just started messing with Python, and was having a great time with entering Tkinter GUI commands into the Python shell (ActivePython 2.5).
Its fun entering commands one at a time and seeing components appear real-time (instead of normal process of having to compile the whole thing first).

Anyway, I was wondering if there was a way to paste multiple lines of source code (at once).

Also: Is there a function that causes a string to be interpreted as a command?

I suggest the standard IDLE instead. I found ActivePython lacking in features (dedent region, indent region, comment region, uncomment region) yet containing no new (useful) ones.

As for pasting multiple lines: well, you can paste multiple lines, but it only seems to evaluate the first one.

What you can instead do is nest those multiple lines in a function, and then paste it.

def test():
  line1 = 'bah'
  line2 = 'foo'
  print line2 + line1

now type test() for the result 'foobah'

whereas

line1 = 'bah'
line2 = 'foo'
print line2 + line1

would only evaluate line1 = 'bah'

This is only marginally easier than creating an actual script, since you get to avoid creating a file just for a test.

Re using strings as commands... what's the context?

Oh, and I highly recommend wxPython over Tkinter. Much more powerful, intuitive and easy to use, IMHO. Also newer: http://www.wxpython.org/quotes.php

Note the words by Eric …

Fuse 17 Light Poster

Then let me write one for you:

import wx

app = wx.App() # create a wx application

window = wx.Frame(None, title = 'Sample GUI App') # create a window
btn = wx.Button(window) 
# 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.

window.Show() # make the frame and button visible
app.MainLoop() # keep things going

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. Onwards:

import wx

app = wx.App()

window = wx.Frame(None, title = 'Sample GUI App',
                  pos = (100,100), size = (400,500))
helloBtn = wx.Button(window, label = 'Hello',
                pos = (400 - 60 - 15, 10), size = (60,25))
byeBtn = wx.Button(window, label = 'Bye',
                pos = (400 - 120 - 15, 10), size = (60,25))
printArea = wx.TextCtrl(window,
                        pos = (10, 10), size = (400 - 120 - 15 - 10, 25),
                        style = wx.TE_READONLY)
window.Show()
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 …

vegaseat commented: great intro to wxPython +8
Fuse 17 Light Poster

I learnt wxPython yesterday. I tried Tkinter at first, but disliked it. Here's a summary of why: http://www.wxpython.org/quotes.php

It's really easy to learn and understand. The trouble is there's little sample code and many tutorials on it are out of date because it seems to change a fair bit each revision.

I recommend this post here as a good reference: http://www.daniweb.com/forums/post335474-3.html

You might also be interested in my application which is fairly simple but a good example of a working wxPython app: http://www.daniweb.com/forums/thread127935.html