How do I create a popup menu
Menus don't just pull down from menu bars at the top of your frame. They can also pop up from anywhere in the frame. Most of the time, a pop-up menu is used to provide actions that are context-sensitive, and that relate to the object at the location where the user clicks. Figure 10.6 displays an example of pop-up menus in action. Pop-up menus are created very similarly to standard menus, however, they are not attached to the menu bar. Listing 10.9 displays the code for a sample popup menu....
How can I perform a print preview
One of the advantages of the device contexts as they are implemented in wxPy-thon is that it makes it easy to manage print preview, since most of the functionality comes from just replacing the printer device context with a screen device context. However, the print preview API is a bit different than for regular printing. For one thing, since print preview takes place on screen in a window, wxPy-thon provides a frame class for previewing. The next three sections describe the print preview...
Understanding the application object lifecycle
The lifecycle of your wxPython application object begins when the application instance is created and ends just after the last application window is closed. This does not necessarily correspond to the beginning and ending of the Python script that surrounds your wxPython application. The script may choose to do some activity before creating the wxPython application, and may do further cleanup after the application MainLoop exits. All wxPython activity, however, must be performed during the life...
How do I manage the row and column headers of a grid
In a wxPython grid control, each row and column has its own label. By default, rows are given numeric labels starting with 1 and columns are given alphabetical labels starting with A and continuing to Z, which is followed by aa, ab, and so on. If you're creating a spreadsheet, this is great, but not necessary for most other applications. For something a bit less generic, wxPython provides methods to change the labels. Figure 14.3 displays a sample grid with label headers. Figure 14.3 A sample...
Redirecting output
If wxPython is controlling the standard streams, then text sent to the streams via any mechanism including a print statement or a system traceback is redirected to a separate wxPython frame. Text sent to the streams before the wxPython application begins or after it ends is, of course, processed normally. Listing 2.1, demonstrates both the application lifecycle and the stdout stderr redirection. Listing 2.1 A sample startup script showing output stream redirection def _init_ self, parent, id,...
Setting values in a multicolumn list
You may have noticed that inserting an item using the row methods described earlier only sets the initial column of a multi-column report list. To set the strings in other columns, use the method SetStringltem . SetStringItem index, col, label, imageId -1 The index and col parameters are the row and column indexes for the cell you are setting. You can set the col parameter to 0 to set the first column, but the index must correspond to a row that already exists in the list control in other...
Advanced wxPython
It n this part we start with three more complex widget objects, and move to features that won't be a part of every wxPython program, but are good to know for the times when you will need to, say, print something. In chapter 13, Building list controls and managing items, we cover the list control. More advanced than the simple list box, the list control allows a full Windows Explorer-like display, complete with different modes. You'll see how to switch between modes, add text and images to the...
Creating tree controls and adding items
A tree control is an instance of the class wx.TreeCtrl. Figure 15.1 displays a sample tree control. Listing 15.1 shows the code used to generate that example. Notice that the tree is driven by an external structure stored in a file called data.py. We won't print that file here, but it is available at the book's web site. It consists of a nested list structure of the wxPython class hierarchy, a convenient data set for a tree control. Some of the mechanisms in this sample are discussed later in...
Climbing the tree control
15.1 Creating tree controls and adding items 461 How do I add a root 463 How do I add more items to the tree 463 How do I manage items 464 15.2 What styles control the display of the tree control 465 15.3 Sorting elements of a tree control 467 15.4 Controlling the image for each item 468 15.5 Navigating the tree programmatically 471 15.6 Managing the tree selection 472 15.7 Controlling which items are visible 473 15.8 Making a tree control user editable 477 15.9 Responding to other user events...
Climbing the tree control 1
Creating a tree control and adding items Using styles to design the tree control Navigating the tree programmatically Managing the tree selection Controlling the visibility of items The tree control is the last of the three wxPython controls for displaying complex data. In this case, the tree control is designed to show data with a strong hierarchy, where you can see that each piece of data has parent and child relationships. One standard example is a file tree, where directories have...
How can I learn more about list controls
Sometimes, you'll need to determine which item is selected in a list from someplace else in your program, or you'll need to change which item is currently selected programmatically in response to a user event, or to something happening internally in your program. There are several related methods for finding the index of an item in the list, given some other piece of information about the item, as displayed in table 13.7. Table 13.8 displays possible components of the flags return value from...
Putting it together the wxPython toolkit
While both Python and wxWidgets are pretty great on their own, they combine to create an even greater whole, like peanut butter and chocolate. The flexibility of the Python language makes wxPython much easier to develop in than its C counterpart, while the native C code of wxWidgets gives the Python GUI both the speed and native look and feel it would otherwise lack. Table 1.2 gives a sample of some issues that are difficult to manage in C but easy, if not trivial, in Python. Table 1.2...
C
C 20-27, 44, 97-98, 103, 130, 154, 189, 202, 235, 464, 502 adding a root 463 bridging gaps with Python code 80 destructor 153, 371 different from Python 84 expected data type 413 interaction with Python 28 macros in 63 manages image list 402 manages memory 362 naming conventions 33-34 object names 9 overridden by Python 78 Python class subclasses 446 sorting a tree control 467 threading tools 543 toolkit 9-10 user input 490 wxWidget set 282 calltips 85, 88, 94, 97, 106 CaptureMouse 152 cell...
How do I make a button with a bitmap
Occasionally, you'll want a picture on your button, rather than a text label, as in figure 7.5. In wxPython, use the class wx.BitmapButton to create a button with a picture. The code to manage a wx.BitmapButton is very similar to the general button code, as displayed in listing 7.5. Listing 7.5 Creating a bitmap button wx.Frame._init_ self, None, -1, 'Bitmap Button Example', size 2 00, 150 panel wx.Panel self, -1 bmp wx.Image bitmap.bmp, wx.BITMAP_TYPE_BMP .ConvertToBitmap self.button...
How do I create a frame
We've already seen numerous examples of frame creation in this book, but at the risk of repeating ourselves, we'll review the initial principles of frame creation. Frames are instances of the class wx.Frame. Listing 8.1 displays a very simple example of frame creation. if __name__ '__main__' app wx.PySimpleApp frame wx.Frame None, -1, A Frame, style wx.DEFAULT_FRAME_STYLE, size 2 00, 100 frame.Show app.MainLoop This creates a frame with the title A Frame, and a size of 200 by 100 pixels. The...
A unittest sample
Listing 5.13 shows a sample unittest module, in this case, tests for the model example in Listing 5.12. Listing 5.13 A sample unit test for the model example import unittest import modelExample import wx class TestExample unittest.TestCase self.frame modelExample.ModelExample parent None, id -1 def tearDown self d Tear down after each test def testModel self lt -J a test self.assertEqual Barney, self.frame.model.first, msg First is wrong lt 1- L An assertion self.assertEqual Rubble,...
Syntax highlighting
As you enter code into the shell, PyCrust changes the color of the text depending on its significance. For example, Python keywords appear in one color, literal string values in another, and comments in yet another. This provides a visual confirmation that you haven't missed any trailing quotes, or misspelled a Python keyword. Many of the features of PyCrust are made possible by a very powerful text control distributed with wxPython. The wx.stc.StyledTextCtrl is a wxPython wrapper of the...
Dynamic updating
All of PyCrust's shell features are updated dynamically as you run PyCrust, which means that features such as autocompletion and calltips are available even on objects defined at the shell prompt. For example, take a look at the sessions shown in figures 4.6 and 4.7 where we have defined and made use of a class. In figure 4.6, PyCrust displays the autocompletion options available for this new class. In figure 4.7, PyCrust displays a call tip for the newly defined method of the class. Figure 4.6...
Managing thread communication with the queue object
Although using CallAfter is the easiest way to manage thread communication, it's not the only mechanism. You can use Python's thread-safe Queue object to send command objects to the UI thread. The UI thread should be written to take commands from this queue in a wx.EVT_lDLE event handler. Essentially, you will be setting up a parallel event queue for thread communication. The command objects can be whatever makes sense for the application, ranging from simple data values to thread objects whose...
How do I create a grid with a grid table
In more complicated cases, you can keep your data in a grid table, which is a separate class that stores the data and interacts with the grid control to display the data. The grid table is especially recommended where the data from the grid is complex the data is already stored in other objects in your system the grid is large enough that it should not all be stored in memory at once In chapter 5, we discussed grid tables in the context of the MVC design pattern, along with different ways of...
Namespace tab
The Namespace tab, displayed in figure 4.8, is split into two parts, again using the wx.SplitterWindow control. The left-hand side contains a tree control that displays the current namespace, while the right-hand side displays details about the object currently selected in the namespace tree. 1 PyCrust 0.9.4 - The Flakiest Python She LI 2 Sponsored by Orbtech - Your source for Python programming expertise. 3 Python 2.3.3 1, Jan 2S 2004., 11 06 18 4l GCC 3.2.2 Mandrake Linux 9.1 3.2. 2-3mdk on...
Display tab
The Display tab displays a pretty print view of an object. PyCrust has a built-in function, pp , that uses Python's pretty print module pprint to produce a nicely formatted view of any wxPython object. However, instead of requiring you to explicitly import and use pprint repeatedly, the information in the Display tab is updated every time the displayed object is updated. For example, to see how the contents of a list change as you manipulate it in the shell, you can make the Display tab the...
How can I create my own events
Although a more advanced topic, this is the most obvious place to discuss custom events. On a first reading, you can probably skip it and come back later. In addition to different event classes supplied by wxPython, you can create your own custom events. You can do this in response to data updates or other changes that are specific to your application, where event instances are required to carry your custom data. Another reason to create a custom event class could be to support a custom widget...
How do I interact with a wxPython program
A compelling feature of Python compared to other programming languages is that it can be used in two ways you can use it to run existing programs written in the Python language, or you can run Python interactively from a command prompt. Running Python interactively is similar to having a conversation with the Python interpreter. You type in a line of code and hit Enter. Python executes the code, responds, and prompts you for the next line. It is this interactive mode that sets Python apart from...
Working with applications and frames
Once you've imported the wx module, you can create your application and frame objects. Every wxPython program must have one application object and at least one frame object. These objects will be discussed in detail in chapter 2. For now, you just need to know that the application object must be an instance of wx.App or of a subclass you define where you declare an OnInit method. The OnInit method will be called by the wx.App parent class when your application starts. Subclass the wxPython...
Working with wxFrame styles
The wx.Frame constructor takes a bitmask as a style parameter. Every wxPython widget object takes a similar style parameter, although the exact values that are defined are different for each type of widget. This section will discuss the styles used for wx.Frame. At least some of this is applicable to other wxPython widgets. The widget definitions in part 2 will discuss styles applicable to each class. WHAT'S A A bitmask is a way of compactly storing information about system attributes that is...
Python help
PyCrust provides full support for Python's help functionality. Python's help function displays information about almost all aspects of Python, as displayed in figure 4.5. 1 PyCrust 0.9.4 - The Flakiest Python Shell 2 Sponsored by Orbtech - Your source for Python programming expertise. 3 Python 2.3.3 1, Jan 25 2004, 11 06 18 4 GCC 3.2.2 Mandrake Linux 9.1 3.2.2-3mdk on linux2 5 Type help, copyright, credits or license for more information. 7 Type help for interactive help, or help object for...
Can I see a realworld example of sizers in action 1
So far, the sizer examples we've shown have been deliberately contrived to display the functionality of the sizers. However, you might be wondering how to use sizers to build a real layout, and we hope the folowing example will give you some ideas. Figure 11.16 shows a moderately complicated layout built with various sizers. The code used to create figure 11.16 is shown in listing 11.11. The code looks complex, but we'll go through it piece by piece. Listing 11.11 Using sizers to build the...
The wxPython printing framework 1
Creating and displaying the print dialog Creating and displaying the page setup dialog Printing from your application In chapter 16, we looked at one method of printing in wxPython using wx.Html-EasyPrinting. This works fine if you are trying to print HTML or something that can easily be converted to HTML , but is somewhat lacking as a complete printing solution. There is a more general printing framework in wxPython, which you can use to print anything and everything you want. Essentially,...
What is report mode
In report mode, the list is displayed in a true multi-column format, with each row able to have an arbitrary number of columns attached to it, as displayed in figure 13.4. wx.ListCtrl in wx.LC_REPORT mode Wishlist - wxDbGetConnection return value wxPostscriptDC with floating point coordinates Wishlist - Better wxString Formatting Wishlist - Crossplatform wxRichText Widget Support for paper trays when printing FloatCanvas demo should work with numarray wxGrid Support for Search Replace...
How do I print in wxPython
We'll start with the wx.Printout class. Like frames, and unlike many of the widget classes, you'll create your own custom subclass of wx.Printout. Next, you will override methods of wx.Printout to define your custom printing behavior. There are seven methods of wx.Printout that you can override to customize how the printout object does its work. These methods are automatically called by wxPython during the course of a printing session. Figure 17.1 displays six of these methods Figure 17.1 The...
How do I find a subwidget of a frame
Occasionally, you'll need to find a specific widget on a frame or panel without already having a reference to that widget. A common application of this, as shown in chapter 6, is to find the actual menu item object associated with a menu selection since the event doesn't hold a reference to it . Another use case is when you want an event on one item to change the state of an arbitrary other widget in the system. For example, you may have a button and a menu item that mutually change each...
Command recall
There are many ways to avoid typing within the PyCrust shell. Most of them involve capturing something you have previously entered, modifying it if necessary, and sending it to the Python interpreter. For example, PyCrust maintains a history of all the commands you have entered in the current session. You can recall any previously entered Python commands single-line or multi-line from the command history. Table 4.1 displays a list of keyboard shortcuts that relate to this functionality. Table...
How do I respond to a menu event
In the last section, we displayed two code examples that respond to a menu selection. Like many of the widgets we saw in chapter 8, selecting a menu item triggers an instance of wx.CommandEvent of a specific type. In this case, the type is wx.EVT_MENU. Menu item events vary from other command events in the system in two ways. First, the Bind function that associates the menu item event with a specific function is called, not on the menu item instance or its containing menu or menu bar...
How do I create a submenu
If your application becomes too complex, you can create a submenu inside a toplevel menu, which allows you to nest menu items and fit more items within a top-level menu. Submenus are particularly useful at grouping a set of options that belong together logically, especially when there would be too many options to fit comfortably at the top-level. Figure 10.5 displays a sample wxPython application with a submenu. Listing 10.8 displays the code used to generate the figure. Listing 10.8 Building a...
Standard shell environment
As much as possible within the wxPython environment, PyCrust behaves the same as the command line Python shell. This includes some unusual situations, such as pickling instances of classes that are defined within a shell session. One area where PyCrust falls short in its ability to duplicate the command line functionality is keyboard interrupts. Once Python code has been entered into the PyCrust shell, there is no way to interrupt the execution of the code. For example, suppose you coded an...
Dispatcher tab
PyCrust includes a module named dispatcher that provides a mechanism to loosely couple objects in an application. PyCrust uses this dispatcher to keep aspects of its interface updated, primarily when commands are sent from the shell to the Python interpreter. The Dispatcher tab figure 4.9 lists information about signals routed through its dispatching mechanism. It's primarily useful when working with PyCrust itself. The Dispatcher tab also illustrates how to add another tab to a wx.Notebook...
How do I respond to text events
There are a handful of command events generated by wx.TextCtrl widgets that you may want to use. All of these events are bound to the text widget in question, so you need to pass it to the Bind method to catch the event, as in the following frame.Bind wx.EVT_TEXT, frame.OnText, text Table 7.8 describes these command events. Generated when the text in the control changes. This event is generated both in response to user input, and to the programmatic change via the SetValue method. Generated...
Autocompletion
Autocompletion occurs when you type in the name of an object followed by the dot operator. PyCrust displays an alphabetical listing of all known attributes for that particular object. As you enter additional letters, the highlighted selection in the list changes to match the letters you have entered. If the item you want is highlighted, press the Tab key and PyCrust fills in the rest of the attribute name for you. In figure 4.3, PyCrust is displaying a list of attributes for a string object....
How can I respond to a user selection in a column header
In addition to events that are triggered by a user event within the main body of the list, there are events that are triggered by user activity in the column headers of a report list control. The wx.ListEvent objects created by a column event have another property, GetColumn , that returns the index of the column in which the event takes place. If the event is a drag event of a column border, the index is for the column on the left side of the border being dragged. If the event is triggered by...
How do I use standard file dialogs
Most GUI applications must save and load data of some kind or another. For the sanity of both you and your users, having a single, consistent mechanism for choosing files is desirable. Happily, wxPython provides the standard dialog wx.FileDialog to insert into your applications for this purpose. Under MS Windows, this class is a wrapper around the standard Windows file dialog. Under an X Window system, this is a similar looking custom dialog. Figure 6.5 displays the file dialog for the sketch...
How can I edit a label
Editing an entry in the list is simple, except in report lists, where the user can only edit the first column in each row. For other kinds of lists, that's not an issue the regular label for each item is editable. To make a list editable, include the style flag wx.lc_edit_labels in the constructor when the list is created. list wx.ListCtrl self, -1, style wx.LC_REPORT wx.LC_EDIT_LABELS If the edit flag is set, the user can start an edit session by clicking on a list item that has already been...
How do I create a toggle menu item with a checkbox or radio button
Menu items are not only used for getting user input in the form of selections, they can also be used to display the state of the application. The most common mechanism for displaying state via a menu item is the use of a toggle menu item that emulates a checkbox or radio button you can also just change the text of the menu item or use the enabled disabled status to reflect application state . Figure 10.4 displays an example of both checkbox and radio menu items in action. As you might expect...
What is an image list and how do I add images to it
Before we can talk about how information is added to the list control, we need to say a few words about how a list control manages images. Any image used within a list control must first be added to an image list, which is an indexed array of images stored with the list control. When associating an image with a specific item in the list control, the index of the image within the image list is used to refer to the image, rather than using the image itself. This mechanism ensures that each image...
Creating and using wxPython menus 1
Adding submenus, pop-up menus, and custom menus Usability guidelines for menus It's difficult to imagine an application without the familiar bar at the top starting with File and Edit and ending with Help. Menus are such a common part of the standard interface kit that they tend to fade into the background without drawing much attention. That's too bad, because the way that menus give the user access to all functionality quickly and easily was truly revolutionary. In wxPython, there are three...
What can wxPython do
Nearly all of your interface needs can be filled by wxPython. In this section, we'll show you what some of the wxPython toolkit looks like, using pictures from elements of the wxPython demo application. Figure 1.8 is a composite image showing all the basic widgets you'd expect buttons, checkboxes, a combo box, menus, list box, a spinner control, text controls and radio buttons. Figure 1.9 shows less common, but very useful widgets, including a slider control, an editable list box, a time...
Can I combine a checkbox and a list box
You can combine a checkbox with a list box using the class wx.CheckListBox. Figure 7.14 displays a checkbox and a list box together. The constructor and most methods of wx.Check-ListBox are identical to wx.ListBox. There is one new event, wx.evt_checklistbox, which is triggered when one of the checkboxes in the list is clicked. There are two new methods for managing the checkboxes Figure 7.14 A check list box is very similar to a regular list box Check n, check sets the check state of the item...
What are the useful features of PyCrust
Now we will look at some of the shell features that PyCrust provides. The PyCrust shell looks familiar because it displays the same information lines and uses the same prompts as the command line Python shell. Figure 4.2 displays an opening PyCrust screen. You'll notice that the PyCrust frame, which contains a wx.SplitterWindow control, is divided into two sections the top section looks like the regular Python shell, the bottom section contains a Notebook control that includes a variety of tabs...
Creating the timer
To create a timer, first create a wx.Timer instance using this constructor. The owner parameter is some instance implementing wx.EvtHandler, meaning any wxPython widget or anything else that can receive event notifications. The optional id is used to differentiate this particular timer from any others. If it is not specified, wxPython will generate an ID number for you. If you don't want to set the owner and ID parameters when you create the timer, you can do so at any time using the method...
Understanding the printout lifecycle
You start a printing session by creating an instance of your printout object, and also an instance of the class wx.Printer. The optional data parameter is an instance of wx.PrintDialogData. To start the actual printing, call the Print parent, printout, prompt True method of wx.Printer. The parent parameter is the parent window for the printing it's used as the parent window for any dialogs that are invoked . The printout parameter is your wx.Printout instance. If the prompt parameter is True,...












