Preface

The wxPython part of the story actually begins in 1995, with Harri Pasanen and Robin Dunn. Robin, who is one of the co-authors of the book, wrote the following about the history of wxPython, and we decided that it was a story better told in his own voice than paraphrased In 1995 I was working on a project that needed a GUI to be deployed on HP-UX systems, but my boss also wanted to show something at a trade show on his Windows 3.1 laptop in a few weeks' time. So I started searching for a cross...

The unittest module

When writing user tests, it's helpful to use a pre-existing test engine to spare you the repetitive task of writing code to run your tests. Since version 2.1, Python has been distributed with the unittest module. The unittest module implements a test framework called PyUnit (a Tkinter based user interface for unittest and some other goodies are available at http pyunit.sourceforge.net ). A PyUnit module is made up of tests, test cases, and test suites. Table 5.5 defines the three groups. Table...

Whats a sizer

A wxPython sizer is an object whose sole purpose is to manage the layout of a set of widgets within a container. The sizer is not a container or a widget itself. It is just the representation of an algorithm for laying out a screen. All sizers are instances of a subclass of the abstract class wx.Sizer. There are five sizers provided with wxPython, defined in table 11.1. Remember, sizers can be placed inside other sizers to give you even more flexibility. Table 11.1 The predefined sizers in...

How can I manage which cells are selected or visible

In a grid control, one or more cells can be selected by the user. In wxPython, there are several methods that allow you to manipulate the group of selected cells. You can also locate the exact cell containing the cursor, and the exact screen position of any specific cell in the grid. At any given time, the selection in a grid control can be zero or more of the following a collection of individually selected cells a collection of selected rows a collection of select columns a collection of...

Adding widgets to a frame

Figure 2.8 shows a custom frame subclass called InsertFrame. When the close button is clicked, the window will close and the application will end. Listing 2.3 defines the wx.Frame subclass shown in figure 2.8. Not all of the concepts in this snippet have been covered yet, so don't worry if some things are not clear. Figure 2.8 The InsertFrame window is an example demonstrating the basics of inserting items into a frame. Figure 2.8 The InsertFrame window is an example demonstrating the basics of...

Getting started with wxPython

We're going to start by working on a real wxPython program, albeit a simple one. We won't create anything complicated, yet. For now, we're going to lead you step-by-step through the process of creating your very first wxPython program. Let's begin by making sure you've got everything installed. Table 1.1 shows everything you'll need in order to run wxPython. Once the installations are complete, get ready to type. We're going to create a program that displays a single image file. This will...

Multi Column Checkbox List Wxpython

The list control is wxPython's widget for displaying lists of information. It is more complex and fully featured than the simpler list box widget. List controls are instances of the class wx.ListCtrl. A list control can be displayed in icon mode, with each item text displaying below an icon, or small icon mode with smaller icons. In list mode the elements display in columns, wrapping from the bottom of one to the top of the next and in report mode, the list displays in multi-column format with...

The wxWidgets toolkit

The other base component of wxPython is the wxWidgets toolkit. At base, wxWidgets is a GUI framework implemented in C , which means it is a set of C classes that encapsulate a wide range of features. Although the primary use of wxWidgets is for UI applications, it also contains useful features for C programmers including C implementations of data structures not supported in ANSI C , such as strings and hashtables, as well as interfaces for system features like sockets and threads. Since these...

Creating the bare minimum wxPython program

Let's begin with the simplest possible wxPython program that will run successfully. Create a file named bare.py and type in the following code. Remember, in Python, the spacing at the start of each line is significant. frame wx.Frame parent None, title 'Bare' There's not much to it, is there Even at only eight lines of code not counting blank lines this program might seem like a waste of space, as it does little more than display an empty frame. But bear with us, as we'll soon revise it, making...

A refactoring example

To show you how these principles work in action, we'll walk you through a refactoring example. Figure 5.1 shows a window that might be used as the front end to a Microsoft Access-like database. This layout is a little more complex than those we have seen so far, but by the standard of real-world applications, it is still quite simple. Listing 5.1 shows a poorly structured way to produce Figure 5.1. When people talk about UI code being a mess, this is what they mean. Having several problems...

A custom model

The basic idea behind creating your model objects is simple. Construct your data classes without worrying about how they will be displayed. Then document a public interface for that class which will be accessible to the display objects. Obviously, the size and complexity of the project will determine how formal this public declaration needs to be. In a small project, with simple objects, it's probably enough to do the simple thing and allow the View objects direct access to the attributes of...

Setting label sizes

The label area on the grid has a separate set of sizing functions. In this case, you are setting the width of the row labels, and the height of the column labels, which means you are treating the column labels as a special row, and the row labels as a special column. As an example, look at a spreadsheet and notice how the row and column labels are laid out. The setter methods are SetRowLabelSize width , which sets the width of the row labels, and SetColLabelSize height , which sets the width of...

What is a grid sizer

The simplest sizer offered by wxPython is the grid. As the name implies, a grid sizer places its children in a two-dimensional grid. The first widget in the sizer's child list goes in the upper left corner of the grid, and the rest are laid out left-to-right and top-to-bottom, until the last widget is placed in the bottom right of the grid. Figure 11.1 shows an example, with nine widgets placed in a 3 x 3 grid. Notice that there is a slight gap between each widget. When you resize the grid...

How can I display the page title in a frames title bar

One thing you've probably noticed in your web browser is that the display window is not the only element of the browser. Among the other elements of note are a title bar and status bar in the containing frame. Typically, the title bar displays the title of the HTML page being displayed, and the status bar displays information about links as they are moused over. In wxPython, there are a couple of shortcuts that allow you to set this relationship up quickly and easily. Figure 16.3 displays this...

Using the Skip method

The first handler function found for an event halts processing on that event unless the Skip method of the event is called before the handler returns. Calling Skip allows additional handler bindings to be searched for, following the rules described in step 4 of 3.4.1, so parent classes and parent windows are searched just as if the first handler didn't exist. In some cases, you want the event to continue processing to allow the default behavior in the native widget to be executed along with...

What styles control the display of the tree control

The display styles for the tree control fall into four basic categories. The first set defines whether the tree control has explicit buttons displayed next to the text of a parent object as a target for expanding or collapsing the parent node. These are displayed in table 15.1. Table 15.1 Button codes for the tree control Table 15.1 Button codes for the tree control The tree control has whatever buttons are typical for the platform. For example on MS-Windows a small button is used to indicate...

How do I create a list control

A wxPython list control is an instance of the class wx.ListCtrl. The constructor is similar to the other widget constructors, as shown here wx.ListCtrl parent, id, pos wx.DefaultPosition, size wx.DefaultSize, style wx.LC_ICON, validator wx.DefaultValidator, name listCtrl These parameters contain values from other widget constructors we have seen. The parent is the containing widget, the id is the wxPython identifier, with -1 indicating automatic creation. Explicit layout is managed by pos and...

Working with wxFrame

In wxPython parlance, a frame is the name given to what a GUI user normally calls a window. That is to say, a frame is a container that the user can generally move freely around on the screen, and which often includes such decorations as a title bar, menubar, and resize targets in the corners. The class wx.Frame is the parent class of all frames in wxPython. There are also a few specialized subclasses of wx.Frame that you may use. This section will give an overview of the wx.Frame family enough...

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

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

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

How do I create a grid with a grid table

Wxpython Table Grid

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

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

Can I see a realworld example of sizers in action

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

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

Wxpython Filedialog Select Folder

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

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

What are the useful features of PyCrust

Nested Wxsplitterwindow

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

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

How do you add or remove children from a sizer

The order in which child widgets are added to the sizer is very important. This is different from the general case of adding children to a parent widget. The typical layout algorithm for a sizer takes each child one at a time in order to determine its place in the display. The placement of the next item is dependent on where the previous items have already gone. For example, the grid sizer moves left to right and top to bottom based on the order of the widgets. In most cases, when you create...

Can I specify a minimum size for my sizer or its children

Another important factor in the layout of widgets within a sizer is the ability to specify a minimum size for the sizer itself or for any of its children. Often, you don't want a control or a sizer to get smaller than a particular size, usually because it will cause text to be cut off by the edge of the widget. Or, in the case of a nested sizer, an entire widget might no longer be displayed inside the window. Given their normal placement within a dialog, the OK and Cancel buttons are common...

Whats a box sizer

The box sizer is the simplest and most flexible of the sizers provided by wxPy-thon. A box sizer is a single vertical column or horizontal row, with the widgets being laid out in a line from left to right or top to bottom. Although this may sound too simplistic to be of any use, the real power of the box sizer comes from the ability to nest sizers inside each other, giving you the advantage of being able to easily place a different number of items in each row or column. And since each sizer is...

How do I lay out widgets

One way to lay out your widgets in your wxPython application is to explicitly specify the position and size of every widget when it is created. Although this method is reasonably simple, over time it has a few flaws. For one thing, because widget sizes and default font sizes differ, it can be very difficult to get the positioning exactly right on all systems. In addition, you must explicitly change the position of each widget every time the user resizes the parent window. This can be a real...

How do sizers manage the size and alignment of their children

Wxpython Align Center Widgets

When a new item is added to a sizer, the sizer uses either the initial size of the item, or the item's best size if there is no initial size set, in its layout calculations. In other words, the sizer does not adjust the size of an item until the sizer is asked to, usually in the context of a window being resized. When the sizer parent widget is resized, the sizer needs to change the size of its components in response. By default, the sizer keeps the widget aligned to the top and left of its...

What are the methods and properties of wxFrame

The tables in this section contain the most basic properties of wx.Frame, and its wx.Window parent class. Many of these properties and methods are covered in more detail elsewhere in the book. Table 8.4 contains some of the publicly readable and modifiable properties of wx.Frame. Table 8.4 Public properties of wx.Frame Table 8.4 Public properties of wx.Frame GetBackgroundColor SetBackgroundColor wx.Color The background color of a frame is the color chosen for any part of the frame not covered...

What is a Model ViewController system

The Model contains what is often called business logic, or all the data and information manipulated by your system. The View contains the objects that display the data, and the Controller manages the interaction with the user and mediates between the Model and the View. Table 5.3 summarizes the components. Table 5.3 The components of standard MVC architecture Table 5.3 The components of standard MVC architecture Business logic. Contains all the data...

How do I add and delete rows columns and cells

Even after the grid has been created, you can still add new rows and columns. Note that the mechanism works differently depending on how the grid was created. You can append a column at the right of your grid using the method AppendCols numCols 1 . To append a row at the bottom of your grid, use the analogous method AppendRows numRows 1 . If you want to add a row or column other than the end of your grid, you can use the method InsertCols pos 0, numCols 1 or lnsertRows pos 1, numRows 1 . In...

How do I create a simple grid

Although the grid control has a huge number of methods to control the precise display and management of its data, getting started with a grid control is straightforward. Figure 14.1 displays a sample grid, with some string data added to each cell. Grid controls are instances of the class wx.grid.Grid. Because of the size of the grid class and related classes, and the fact that many programs do not use it, the wxPython grid classes are in their own module that is not automatically imported into...

Creating logical item groups

You should never have a grouping of more than five items without a separator, unless there's a very strong logical reason to do so such as a history list, or a list of plugins. Groups of more than five items tend to be very difficult for people to process. To have a larger group, the items would need to be very strongly linked together and have a reason why the user would expect the list to be longer than five items. Adhere to standards when ordering menus You should always stick to the...

How do I create a multiline or styled text control

You can create a multi-line text control using the wx.te_multiline style flag. If the native widget has support for styles, you can change font and color styles within the text managed by the control, which is sometimes called rich text. For other platforms, the calls to set styles are simply ignored. Figure 7.3 displays an example of multi-line text controls. Listing 7.3 contains the code used to create figure 7.3. Typically, creating a multi-line control is handled by setting the...

Responding to other user events from a tree control

In this section, we'll discuss the properties of the wx.TreeEvent class. Table 15.6 lists those properties. Table 15.6 Properties of wx.TreeEvent Table 15.6 Properties of wx.TreeEvent Returns the integer key code of the key pressed. Only valid for the event type wx.evt_tree_key_down. This property will not tell you if any modifier keys were also pressed. Returns the wx.TreeItemId of the item which is the subject of the event. Responding to other user events 479 Table 15.6 Properties of...

How do I draw on the screen

To draw on the screen, we use a wxPython object called a device context. A device context abstracts a display device, giving each device a common set of draw methods, so that your draw code is the same no matter what kind of device you are targeting. A device context is represented by the abstract wxPython class wx.DC and its subclasses. Since wx.DC is abstract, you'll need to use one of its subclasses for your application. Table 6.1 displays a field guide to the subclasses of wx.DC and their...

Navigating the tree programmatically

In section 15.1 we mentioned that there was no direct way to get a Python list of the children of a given item in the tree, let alone the index of a specific child. To do that, you need to walk the tree nodes yourself using the methods in this section. To start walking the tree, get the root using GetRootItem . This method returns the wx.TreeItemId of the root item of the tree. You can then use methods such as GetItemText or GetItemPyData to retrieve more information about the item. Once you...

How do I include a submenu or checked menu

In this section, we'll present two common menu tricks, the submenu and the checked or radio menu. A submenu is a menu which is accessible inside one of the top menus. A checkbox or radio menu is a group of menu items that behaves like a group of checkboxes or radio buttons. Figure 6.3 displays a menubar, including a submenu with radio menu items. To create a submenu, build itjust as you would any other menu, and append it to the parent menu using wx.Menu.AppendMenu . Figure 6.3 A menu that uses...

What are some different frame styles

The wx.Frame class has a multitude of possible style flags. Typically, the default style is what you want, but there are several useful variations. The first set of style flags that we'll discuss governs the general shape and size of the frame. Although not strictly enforced, these flags should be considered mutually exclusive a given frame should only use one of them. Using a style flag from this group does not imply the existence of any decorators described in the other tables in this section...

How do I create a font

Fonts are specified as instances of the class wx.Font. You have access to any font that has been installed and is accessible to the underlying system. To create a font instance, use the following constructor wx.Font pointSize, family, style, weight, underline False, faceName , encoding wx.FONTENCODING_DEFAULT The pointSize is the font's integer size in points. The family is used to quickly specify a font without having to know the actual name of the font. The exact font chosen depends on the...

Can I allow the user to browse images

Example For Splitter Window Wxpython

If you are doing graphics manipulation in your program, it's often useful to provide the user with thumbnails of the images while they're browsing the file tree. A wxPython dialog for this purpose is called wx.lib.imagebrowser.Image-Dialog. Figure 9.10 displays a sample. Listing 9.10 displays the simple code for this image browser dialog. Listing 9.10 Creating an image browser dialog import wx.lib.imagebrowser as imagebrowser dialog imagebrowser.ImageDialog None if dialog.ShowModal wx.ID_OK...

Can I combine text entry and a list

The widget that combines text entry and a list is called a combo box, and is essentially a text box bolted to a pull-down choice. Figure 7.17 displays a combo box. On Windows, you can use the right-hand style, which is a text box bolted to a list box. The code for creating a combo box is similar to the choice elements we have already seen. In this case the class is wx.ComboBox, which is a direct subclass of wx.Choice. Listing 7.15 displays the code details. Listing 7.15 Code for a demonstration...

Managing the tree selection

A tree control allows you to programmatically manage the set of selected items in the tree. The basic method for doing this is the method SelectItem item, select True . In a single selection tree control, this method takes a wx.Tree-ItemId and makes that item the current selection, and the previously selected item is automatically deselected. If the select parameter is False, then this method can be used to deselect the currently selected item. In a multiple or extended tree control, then the...

How do I build a splash screen

Displaying a great splash screen with your application provides a professional look for your users. It can also distract the user while your application completes a time-consuming setup. In wxPython, it is easy to build a splash screen from any bitmap using the wx.SplashScreen class. The splash screen can be displayed for a specific length of time, and whether or not the time has been set, the screen always closes when the user clicks on it. The class consists almost entirely of its constructor...

How do I find a specific menu item in a menu

There are a number of ways in wxPython to find a specific menu or menu item given a label or an identifier. You often use these methods in event handlers, especially when you want to modify a menu item or display its label text in another location. Listing 10.4 augments the previous dynamic menu example by using FindltemByld to get the appropriate menu item for display. Listing 10.4 Finding a specific menu item self.txt wx.TextCtrl p, -1, new item btn wx.Button p, -1, Add Menu Item self.Bind...

How can I capture user mouse selections

For the grid control, not only are there several different mouse event types, there are also a few different event classes for those types. The most commonly used event class is wx.grid.GridEvent. The grid event class is a subclass of wx.Command-Event, and provides several methods to get at details of the event, as displayed in table 14.8. Table 14.8 Methods of wx.grid.GridEvent Table 14.8 Methods of wx.grid.GridEvent Returns true if the alt key was pressed when the event was triggered. Returns...

How do I validate data as it is entered

You can also use a validator to validate data entered into the dialog as the user enters it, before the data is passed to the widget. This is very powerful, since it can prevent bad data from getting into your application. Figure 9.15 displays an example, the dialog text explains the idea. This method of validating data is less automated than other mechanisms. You must explicitly bind the character events from the validator's widget to a function, as in the following Figure 9.15 A validator...

How can I get the user to enter text

Moving beyond the mere display of static text, we'll begin discussing user interaction when entering text. The wxPython class for the text entry widget is wx.TextCtrl, which allows both single-line and multi-line text entry. It can also act as a password control, masking the keys pressed. If supported by the platform, the wx.TextCtrl also provides rich text display, with multiple text styles defined and displayed. Figure 7.2 displays a sample of wx.TextCtrl as a single-line control, both with...

How do I bind an event to a handler

Event binders consist of instances of the class wx.PyEventBinder. A predefined instance of wx.PyEventBinder is provided for all of the event types supported, and you can create your own event binders for your custom event types when needed. There is one event binder instance for each event type, which means that multiple binders may correspond to any one wx.Event subclass. This is because event types are more detailed than wx.Event subclasses. For example, the wx.Mouse-Event class has fourteen...

What happens when I close a frame

When you close a frame, it goes away. Eventually. Unless the frame is explicitly told not to close. In other words, it's not completely straightforward. The purpose behind the widget closure architecture in wxPython is to give the closing widget ample opportunity to close documents or free any non-wxPython resources it might be holding onto. This is especially welcome if you are holding onto some kind of expensive external resource, such as a large data structure or a database connection....

PyCrust sets the standard for a Python shell

When you work with Python interactively, you work in an environment that is called the Python shell which is similar to other shell environments, such as the DOS window on Microsoft platforms, or the bash command line on Unix-based systems. The most basic of all the Python shells is the one in listing 4.1, which you see when you launch Python from the command line. While it is a useful shell, it is strictly text-based, rather than graphical, and it doesn't provide all the shortcuts or helpful...

Creating a virtual list control

Let's assume that your wxPython application needs to display a list of all your clients. Initially you use a regular list control, and it works fine. Eventually your use of wxPython makes you more and more successful. Your client list gets longer and longer. Too many clients and your application starts to have performance problems. Perhaps it takes a longer amount of time to start up. Probably it starts using more and more memory. What can you do You can create a virtual list control. The...

Whats a generic button and why should I use one

A generic button is a button widget that has been completely reimplemented in Python, bypassing the use of the native system widget. The parent class is wx.lib.buttons. GenButton, and there are generic bitmap and toggle buttons. There are several reasons for using generic buttons The generic button look is more similar across platforms than native buttons. The flip side is that generic buttons may look slightly different from native buttons on a particular system. Using a generic button, you...

A virtual tree

One interesting use of the expanding and collapsing items is to create a virtual tree where new items are only added when a parent is expanded. Listing 15.3 displays a sample tree with new items added. Listing 15.3 A tree where new items are added dynamically on expansion wx.Frame._init_ self, None, title virtual tree with icons, il wx.ImageList 16,16 self.fldridx il.Add wx.ART_OTHER, 16,16 self.fldropenidx il.Add wx.ART_OTHER, 16,16 self.fileidx il.Add wx.ART_OTHER, 16,16 self.tree wx.TreeCtrl...

How do I create a modal dialog

A modal dialog blocks other widgets from receiving user events until it is closed in other words, it places the user in dialog mode for the duration of its existence. As you can see from figure 9.1, you can't always distinguish between dialogs and frames by their appearance. In wxPython, the difference between a dialog and a frame is not based on how they display, but is largely a matter of the way in which they handle events. A dialog is created and deployed somewhat differently from a frame....

How do I edit a cell

A wxPython grid control allows you to edit cell values in place. For the grid as a whole, editing is on by default. Clicking on a selected cell, or beginning to type a new data value, opens a default string editor that lets you enter a different string. In this section, we'll discuss a number of ways to modify this default behavior. You can shut off the editing for the entire grid with the method Enable-Editing enable the enable parameter is a Boolean. If it is False, no cell in the grid can be...

How can I change an HTML window programmatically

If you are displaying an HTML page, there's a good chance that your frame is behaving like a browser in one way or another. Even if it's not actually browsing the web, it could be browsing help files, or other kinds of linked data. If your user is browsing, the text being changed in your display also needs to change in response to user information. There are a couple of ways to access and change information in the HTML window while it's running. First, you can get the URL of the currently...

How can I display progress

In many programs, the program needs to go off and do something by itself unencumbered by user input. At that time, it's customary for the program to give the user some visual indication that it's actually doing something. In wxPython, that is often managed with a progress box, as displayed in figure 9.5. The sample code to generate this progress box is displayed in listing 9.5. Listing 9.5 Generating a sample progress box Figure 9.5 A sample progress box, joined in progress Figure 9.5 A sample...

Predefined editors

All wxPython editors are subclasses of the class wx.grid.GridCellEditor. Table 14.5 describes the standard editors. In the next section, we'll show you how to create a custom cell editor. Uses a multi-line text control for editing the data value An editor for Boolean cell data, consisting of a checkbox that the user can check or uncheck. It's visually slightly different from the checkbox used by the Boolean renderer. You do not have to have a Boolean renderer to use a Boolean editor you could...

How can I use modules from the Py package in my wxPython programs

Pyqt Tree Examples

What do you do if you don't want an entire PyCrust frame in your application What if you just want the shell interface in one frame, and perhaps a namespace viewer in another And what if you want them to be permanent additions to your program These alternatives are not only possible, they're also fairly easy. We'll end this chapter with one example of how this can be done. We're going to revisit the program we created in chapter 2, the one with a menubar, toolbar, and status bar. We'll add...

Creating a custom renderer

Wxpython Grid Image Cells

To create your own custom cell renderer, create a subclass of wx.grid.PyGridCell-Renderer as with other wxPython classes, the Py version of the class allows for a Python class to subclass the base C class and properly reflect virtual method Figure 14.6 A custom grid renderer, setting background colors Figure 14.6 A custom grid renderer, setting background colors calls to the Python methods. Creating a custom cell renderer allows you to do things like display a numerical value as a mini-bar...

How do I build an about box

An about box is a good example of a display dialog that displays more complex information than is possible in a plain message box, but doesn't require other functionality. In this case, you can use wx.html.HtmlWindow as a straightforward mechanism to display styled text. Actually, wx.html.HtmlWindow is much more powerful than we show here, and includes methods to manage user interaction and rendering in detail. Chapter 16 covers the features of wx.html.HtmlWindow. Listing 6.10 displays a class...

How do I add items to a pulldown menu

There are a couple of mechanisms for adding new menu items to a pull-down menu. The easier is to use the Append method of wx.Menu, as in Append id, string, helpStr , kind wx.ITEM_NORMAL The id parameter is a wxPython ID. The string argument is the string that will be displayed on the menu. The helpStr, if defined, will be displayed in the frame's status bar when the menu is highlighted. The kind argument allows you to set the type of the menu item to a toggle item. Later in this chapter we'll...

How do I display static text

Wxpython Example

Perhaps the most basic task for any UI toolkit is drawing plain text on the screen. In wxPython, this is accomplished with the wx.StaticText class. Figure 7.1 displays the static text control. In a wx.StaticText, you can change the alignment, font, and color of the text. A single static text widget can contain multiple lines of text, however, it cannot handle multiple fonts or styles. For multiple fonts or styles, use a more elaborate text control, such as wx.html.HTMLWindow, described in...

Responding to splitter events

Splitter windows trigger events of type wx.SplitterEvent. There are four different event types of the splitter window, as listed in table 8.10. Table 8.10 Event types of the splitter window Table 8.10 Event types of the splitter window Triggered when the sash is double-clicked. Trapping this event does not block the normal unsplit behavior of this action, unless you call the event Veto method. Triggered at the end of a sash change, but before the change is displayed on screen so you can react...

How do I get short text from the user

The second simple type of dialog box is wx.Text-EntryDialog, which is used to get short text entry from the user. Typically, you'll see this used when requesting a username or password at the beginning of a program, or as a very rudimentary replacement for a data entry form. Figure 9.3 displays a typical text dialog. The code for this example is displayed in listing 9.3. if __name__ __main__ app wx.PySimpleApp dialog wx.TextEntryDialog None, What kind of text would you like to enter , Text...

How can I drag a frame without a title bar

One obvious result of the previous example is that the frame is stuck in the absence of a title bar, there's no standard method of dragging the window. To resolve this problem, we need to add event handlers to move the window when dragging occurs. Listing 8.11 displays the same shaped window as before, with the addition of some events for handling left mouse clicks and mouse moves. This technique is applicable to any other frame, or even to a window inside a frame that you want to move such as...

How can I display HTML from a file or URL

Once you have an HTML window created, the next challenge is to display the HTML text in the window. The following four methods are used to get HTML text into the window. The most direct is the method SetPage source , where the source parameter is a string containing the HTML source that you want displayed in the window. Once you have text in the page, you can append HTML to the end of text that is currently in the window with the method AppendToPage source . For both the SetPage and...

Using a tree list control

In addition to the wx.TreeCtrl, wxPython provides the wx.gizmos.TreeListCtrl which is a combination of a tree control and a list control in report mode. In addition to the features of the wx.TreeCtrl discussed in this chapter, the TreeListCtrl is able to display additional columns of data for each row. Figure 15.3 displays a sample tree list control. A description of wx AcceleratorTable A description of wx.EncodingConverter A description of wx glcanvas .GLContext TJ-fil wx.grid.GridTableBase A...

How do I create a frame with extra style information

The wx.frame_ex_contexthelp style is an extended style, which means that the value of its flag is too large to be set using the normal constructor because of the specific limitations of the underlying C variable type . Normally you can set extra styles after the widget has been created using the SetExtraStyle method, but some styles, such as wx.frame_ex_contexthelp, must be set before the native UI object is created. In wxPython, this needs to be done using a slightly awkward method known as...

How do sizers manage the border around each child

A wxPython sizer can place a border around any or all of its children. The border is a consistent amount of empty space separating the widget from its neighbors. The size of the border is taken into account when the sizer calculates the placement of its children the child is not made smaller to accommodate the width of the border. The size of the border does not change when the sizer resizes. Figure 11.6 shows a 10-pixel border placed around all or part of the widgets in our basic grid layout....

What is a device context and how can I create one

There are ten subclasses of wx.DC in wxPython, split into the following three groups Contexts used for drawing to a screen Contexts used for drawing to a location other than a screen Contexts used to buffer a device context until you are ready to draw it to a screen The first group represents device contexts that draw to the screen. You'd think there would only need to be one of these, but in fact wxPython provides four of them, depending on exactly where you need to draw, and exactly when you...

Whats a miniframe and why would I use it

A mini-frame is just like a regular frame with two primary exceptions it has a smaller title area, and it doesn't display in the window task bar under MS Windows or GTK. Figure 8.8 displays an example of a smaller title area. The code for creating the mini-frame is almost identical to creating a regular frame, the only difference is that the parent class is now wx.MiniFrame. Listing 8.9 displays the code. size 3 00, 100 panel wx.Panel self, -1, size 300, button wx.Button panel, -1, Close Me,...

Creating a splitter window

Wxsplitterwindow

In wxPython, a splitter window is an instance of the class wx.SplitterWindow. Unlike most other wxPython widgets, splitter windows require further initialization after they are created before they can be used. The constructor is pretty straightforward. Figure 8.10 A sample splitter window after initialization Figure 8.10 A sample splitter window after initialization wx.SplitterWindow parent, id -1, pos wx.DefaultPosition, size wx.DefaultSize, style wx.SP_3D, name splitterWindow The parameters...

How do I associate a menu item with a keyboard shortcut

In wxPython you can set up keyboard navigation and shortcuts for menu items. Figure 10.3 displays a sample menu with keyboard decoration added. Notice that the menu names have an underlined character, and that next to the item labeled Accelerated is a Ctrl-A. Studies have shown that keyboard shortcuts are not always the time saver that you think they are. However, they are standard interface elements, and your users will expect them to be there. Shortcuts are also helpful for users with...

How can I create a group of radio buttons

A radio button is a widget that allows the user to choose from among several options. Unlike checkboxes, radio buttons are explicitly deployed in groups and only one of the options can be selected at a time. When a new option is selected, the existing selection is switched off. The name radio button comes from the group of selection buttons on older car radios that exhibited the same behavior. Radio buttons are a bit more complex to use than checkboxes, because they need to be organized into a...

How do I create a checkbox

A checkbox is a toggle button with a text label. Checkboxes are often displayed in groups, but the toggle state of each checkbox is independent. Checkboxes are used when you have one or more options that have clear on off states, and the state of one option doesn't affect the state of the others. Figure 7.10 displays a group of checkboxes. Checkboxes are easy to use in wxPython. They are instances of the class wx.CheckBox, and can be displayed together by placing them inside the parent...

Whats a flex grid sizer

A flex grid sizer is a more flexible version of a grid sizer. It is nearly identical to the regular grid sizer, with the following exceptions It determines a separate size for each row and column. By default, it does not change the size of its cells when resized. You can specify which rows or columns should grow if needed. It can grow flexibly in either direction, meaning that you can specify proportional amounts for individual child elements, and you can specify the behavior in the...

Creating a wizard

A wizard is a series of simple dialogs chained together to force the user to step through them one by one. Typically, they are used to guide a user through installation or a complex setup procedure by breaking down the information into small pieces. Figure 9.11 displays a sample wizard, displaying Back and Next buttons. In wxPython, a wizard is a series of pages controlled by an instance of the class wx.wizard.Wizard. The wizard instance manages the events that take the user through the pages....

How can I change cursors

The cursor is the most direct avatar of the user's presence on the screen. As such, it's used to provide immediate feedback to the user about the area being explored. Normally, it's a pointer to where the user's next mouse click will take effect, but depending on what widget the cursor is currently over, it can be a directional arrow, a text placement I-beam, or crosshairs. Typically, an application signals that it is too busy to accept input by changing the cursor to some kind of busy symbol,...

How this book is organized

We've divided wxPython In Action into three parts. The first part is an introduction to wxPython concepts, a tutorial on how to get started with wxPython, and some information on wxPython best practices. The chapters in part 1 are In this chapter, we introduce wxPython, explain to you why it's the greatest thing since sliced bread, and give some background on the technologies used to create wxPython. Chapter 2, Giving your wxPython program a solid foundation The two most important objects in...

How do I create an alert box

The three simplest ways of interacting with the user via a dialog box are wx.MessageDialog, which represents an alert box, wx.TextEntryDialog, which prompts the user to enter some short text, and wx.SingleChoiceDialog, which allows the user to select from a list of available options. The next three sections discuss these simple dialogs. A message box dialog displays a short message and allows the user to press a button in response. Typically, message boxes are used to display important alerts,...

What can I do with an image

Once you have your image in wxPython, you can manipulate it in numerous useful ways, and use it to write some powerful image adjustment scripts. You can query the size of the image with the methods GetWidth and Get-Height . You can also recover the color value at any pixel with the methods GetRed x, y , GetGreen x, y , and GetBlue x, y . The return value of all these color methods is an integer with a value between 0 and 255 in C terms, it's an unsigned int, but that distinction is not...

Event triggers

In wxPython, most widgets cause higher level events to be fired in response to lower level events. For example, a mouse click within the space of a wx.Button causes the generation of an EVT_BUTTON event, which is a specific type of wx.Command-Event. Similarly, a mouse drag in the corner of a window causes a wx.SizeEvent to be created automatically for you by wxPython. The advantage of these higher level events is that they make it easier for the rest of your system to focus on the most relevant...

How can I use a color picker

The color picker dialog is similar to the font dialog, because it uses an external data class to manage its information. Figure 9.9 displays the MS Windows version of the dialog. Listing 9.9 displays the code to generate the dialog, which is nearly identical to the code seen in the previous section for the font picker. Listing 9.9 Code for a color picker dialog dialog wx.ColourDialog None if dialog.ShowModal wx.ID_OK data dialog.GetColourData print 'You selected s n' str data.GetColour .Get...

How can I create fancier menus

If ordinary menu items aren't interesting enough for you, you can add a custom bitmap to be displayed next to the menu item or used as a custom check symbol . Under MS Windows, you can also adjust the font and color of the menu item. Figure 10.7 displays a fancy menu example. Listing 10.10 displays the code to produce the menu. To determine whether the program is running under Windows, you can check that 'wxMSW' is in the wx.PlatformInfo tuple. Figure 10.7 Menu items with custom bitmaps,...

How do I change the color or font of a grid cell

Wxpython Color Cell

As with other controls, there are a set of properties that you can use to change the display attributes for each cell. Figure 14.5 displays some of what you can do with the attribute methods. Listing 14.6 displays the code used to create figure 14.5. Notice the use of both grid methods aimed at a specific cell and of the creation of wx.grid.Grid-CellAttr objects. Figure 14.5 A sample usage of the grid attribute methods Listing 14.6 Changing the color of grid cells wx.Frame._init_ self, None,...