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

What is icon mode

A list control looks like the display panel of a file tree system like MS Windows Explorer. The control displays a list of information in one of four different modes. The default is icon mode, where each element in the list is displayed as an icon with the text for the item below. Figure 13.1 displays a sample list in icon mode. The code for figure 13.1 is displayed in listing 13.1. Note that listing 13.1 depends on some .png files being in the directory with this module. These files are...

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

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

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

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

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

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

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

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

Dispatcher tab

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

How do I use a standard color picker

It would be useful if the user was allowed to select an arbitrary color in the sketch dialog. For that purpose, we can use the standard wx.ColourDialog provided by wxPython. Use of this dialog is similar to the file dialog. The constructor takes only a parent and an optional data attribute. The data attribute is an instance of wx.ColourData, storing some data associated with the dialog such as the user-chosen color, and the list of custom colors. Using the data attribute allows you to keep the...

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

Step Determining whether to propagate

Eventually wxPython determines whether the event process should propagate up the container hierarchy to find an event handler. The container hierarchy is the path from a specific widget to the top-level frame, moving from each widget to its parent container, and upward. If the current object doesn't have a handler for the event, or if the handler called Skip , wxPython determines if the event should propogate up the container hierarchy. If the answer is No, the process looks once more for a...

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

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

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

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

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 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 can I respond to a user selection in a list

Like other controls, a list control triggers events in response to user actions. You can set handlers for these events using the Bind method, as discussed in chapter 3. All of these event handlers receive an instance of wx.ListEvent, which is a subclass of wx.CommandEvent. The wx.ListEvent has a few getter methods specific to its class. Some of the properties are only valid for specific event types described in other sections of this chapter. The properties common to all event types are...

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

Controlling visibility

There are a number of methods that allow you to manage which items are visible within the display. An object may be not visible either because it has been scrolled off the visible part of its containing frame or because it is part of a child list that is collapsed. You can determine whether an item is visible on the screen with the IsVisible item method which returns True if the item is visible, and False if it is not. You can force an item to become visible by using the method Ensure-Visible...

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

Transferring a custom data object

Although the available data object options of text, bitmap, and list of filenames are flexible enough to cover a variety of uses, sometimes you will need to transfer a custom object, such as your own graphic format, or a custom data structure. Next, we'll cover a mechanism for transferring custom data objects, while retaining control over what kind of data your object will accept. The limitation on this method is that, for reasons that will be abundantly clear in a moment, it only works within...

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

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 can I display a list of choices in a dialog

If allowing your users a blank text entry seems like too much freedom, you can restrict their options by using wx.Single-ChoiceDialog to give them a single choice out of a group of options. Figure 9.4 displays an example. The essential code displayed in listing 9.4 is similar to the dialog examples we've already discussed in this chapter. Listing 9.4 Displaying a dialog list of choices choices Alpha, Baker, Charlie, Delta dialog wx.SingleChoiceDialog None, Pick A Word, Choices, choices print...

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

Welcome to wxPython

Getting started with wxPython Creating a minimum wxPython program Learning the Python programming language Here's a simple wxPython program. It creates a window with one text box that displays the position of the mouse pointer. Counting white space, it's about 20 lines long. Listing 1.1 A working wxPython program in a mere 20 lines wx.Frame._init_ self, None, -1, My Frame, size 300, 300 panel wx.Panel self, -1 panel.Bind wx.EVT_MOTION, self.OnMove wx.StaticText panel, -1, Pos , pos 10, 12...

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

Whats a grid bag sizer

A grid bag sizer is a further enhancement of a flex grid sizer. There are two innovations in the grid bag sizer. The ability to add a widget to a specific cell within the grid. The ability to have a widget span several cells of the grid the way that a cell in an HTML table can . Figure 11.10 A sample grid bag sizer Figure 11.10 shows a sample grid bag sizer. It's very similar to the example we've been using throughout this chapter, with the addition of new widgets to show a sample of a row span...

Around my wxPython application

How Remove Title Bar Wxpython

Let's assume that you've used wxPython to create a program, and your program is working, and now you'd like a better understanding of exactly how it works. You've seen the PyCrust features listed earlier in this chapter, and they look like they could be very useful in gaining insights into the functioning of your program. But you'd rather not change your program just to be able to use PyCrust. What do you do By passing the name of your program to the PyWrap utility, you can start your program...

How do I draw to a device context

Now that you have your device context, you may want to actually draw some pictures of your own onto it. One advantage of the device context concept is that your program does not care which kind of device context is being used the draw commands are the same no matter what. Using wxPython, there are many ways to draw to a device context. The device context API defines about eighteen or so different methods that allow you to draw on the screen. Table 12.4 lists the first batch methods that let you...

Controlling the image for each item

Wxpython Artprovider Icons

The images for the tree controls are managed with an image list in much the same way as images are managed in list controls. For details on creating image lists, see chapter 13. Once you've created the image list, you assign it to the tree control using the method SetImageList imageList or AssignImageList image-List . The former allows the image list to be shared with other controls, and the latter gives ownership of the image list to the tree control. You can later get the image list using the...

How do I use a validator to ensure correct data

A validator object is a subclass of wx.Validator. The parent class is abstract, and isn't used directly. Although there are a couple of predefined validator classes in the C wxWidget set, in wxPython, you will need to define your own validator classes. As we've seen in other cases, your Python classes need to inherit from a Python-specific subclass, wx.PyValidator, to be able to override all the parent methods. A custom validator subclass must also override the method Clone , which should...

How can I create a list box

A list box is another mechanism for presenting a choice to the user. The options are placed in a rectangular window and the user can select one or more of them. List boxes take up less space than radio boxes, and are good choices when the number of options is relatively small. However, their usefulness drops somewhat if the user has to scroll far to see all options. Figure 7.13 displays a wxPython list box. In wxPython, a list box is an element of the class wx.ListBox. The class has methods...

Sorting elements of a tree control

The basic mechanism for sorting elements of a tree control is the method Sort-Children item . The item parameter is, as you should expect by now, an instance of wx.TreeItemId. The method sorts the children of that item from the top of the list downward in alphabetical order of their display strings. There's one quirk to sorting in a tree control. In order for a tree to sort, each tree item needs to have data attached, which is true even if you are going to use the default sort. In the default...

How can I use a font picker

The font picker dialog in wxPython is different than the file dialog, because it uses a separate helper class to manage the information it presents. Figure 9.8 displays the MS Windows version of the font dialog. Listing 9.8 displays the code used to generate figure 9.8, and should look somewhat different than previous dialog examples. Listing 9.8 Sample code for a font picker dialog box if __name__ __main__ app wx.PySimpleApp dialog wx.FontDialog None, wx.FontData if dialog.ShowModal wx.ID_OK...

Column sorting with the mixin class

One common case for sorting a list control is to give the user the ability to sort a list in report view in any column by clicking on the column. You could do that wx.ListCtrl with ColumnSorterMixiri Lj nl wxListCtrl column widths in wxLC_ICON mode Wishlist - wxStaticText that takes fonts, colors, etc. Wishlist - Crossplatform wxRichText Widget wxPostscriptDC with floating point coordinates Wishlist - Better wxString Formatting Wishlist - wxDbGetConnection return value The column sorter mixin...

A wxPython model PyGrid TableBase

Wxpython Listings

The class wx.grid.Grid is the wxPython control for a spreadsheet-style layout of rows and columns. You're probably familiar with the basic concept, but figure 5.3 shows how the wxPython version looks. The grid control has a lot of interesting features, including the ability to create custom renderers and editors on a cell-by-cell basis, as well as dragable rows and columns. Those features will be discussed in greater detail in chapter 13. In this chapter, we'll stick to the basics and show how...

Cut and paste

You may often want to reuse code developed within the shell without having to type it again. At other times, you may find sample code, perhaps from an online tutorial, and you'd like to apply it to a Python shell. PyCrust provides a couple of simple cutting and pasting options, listed in table 4.2. Table 4.2 Keyboard shortcuts related to cutting and pasting in the PyCrust shell Table 4.2 Keyboard shortcuts related to cutting and pasting in the PyCrust shell Copy selected text, removing prompts...

How can I use a file picker

Wxpython File Dialog

File-choosing dialogs tend to be consistent from application to application. In wxPython, the wx.FileDialog uses the native OS dialog for the major platforms, and uses non-native look-alikes for other operating systems. The MS Windows version is displayed in figure 9.6. You can set up the file dialog to start in any directory, and you can also pass it a wildcard filter to limit the display to only certain file types. Listing 9.6 displays a basic example. wildcard Python source .py .py Compiled...

How do I include a toolbar

Menu bars and toolbars are often tightly linked, making most or all of the functionality of the toolbar available via a menu item. In wxPython, this similarity is enhanced by the toolbar buttons emitting wx.evt_menu events when clicked, making it easy to use the same methods to handle both the menu item selection, and the toolbar click. A wxPython toolbar is an instance of the class wx.ToolBar, and as we saw in chapter 2, can be created using the Frame method CreateToolBar . Like a status bar,...

Working with the wxEvt Handler methods

The wx.EvtHandler class defines a number of methods that are not called under normal circumstances. The method of wx.EvtHandler that you will use frequently is Bind , which creates the event bindings that we've discussed so far. The method signature is Bind event, handler, source None, id wx.ID_ANY, id2 wx.ID_ANY The Bind function associates an event and an object with an event handler function. The event parameter is required, and is a wx.PyEventBinder instance as described in section 3.3. The...

Working with wxPrintout methods

There are a few getter-type methods in wx.Printout that allow you to retrieve information about the current print environment. Table 17.1 lists these information retrieval methods. Table 17.1 Information retrieval methods of wx.Printout Table 17.1 Information retrieval methods of wx.Printout This method returns the device context to be used for drawing the document for the printer or the print preview. Returns a 4-element tuple minPage, maxPage, pageFrom, pageTo . The minPage and maxPage return...

How do I manage the foreground drawing pen

The color and style of the lines you draw on your device context are controlled by the current pen, which is an instance of the class wx.Pen. To get the current pen, use the device context method GetPen . Not surprisingly, you can set the current pen with SetPen pen . The wx.Pen class is a simple structure with several properties related to drawing lines. The constructor for wx.Pen lets you set some of the properties. wx.Pen colour, width 1, style wx.SOLID The colour parameter is either a...