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

Working with modal dialogs

Modal dialogs are used for quick interactions with the user or for any time that information in a dialog absolutely must be entered before the user can move forward in the program. Within wxPython, there are several standard functions to display basic modal dialogs. These dialogs include alert boxes, one line of text entry, and choosing from a list. In the following sections, we'll show you what these dialogs look like, and how using the predefined functions will make your life easier.

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

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

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 do I make a button with a bitmap

Occasionally, you'll want a picture on your button, rather than a text label, as in figure 7.5. In wxPython, use the class wx.BitmapButton to create a button with a picture. The code to manage a wx.BitmapButton is very similar to the general button code, as displayed in listing 7.5. Listing 7.5 Creating a bitmap button wx.Frame._init_ self, None, -1, 'Bitmap Button Example', size 2 00, 150 panel wx.Panel self, -1 bmp wx.Image bitmap.bmp, wx.BITMAP_TYPE_BMP .ConvertToBitmap self.button...

How do I create a 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...

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

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

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

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

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

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

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

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

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

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

Working with the support modules

The support modules provide basic functionality for the end-user programs, and can also be imported into your own programs. These modules are essentially the building blocks used to create the user-level Py programs. Table 4.4 displays a listing of the support modules that are part of the Py package, along with a brief description. Contains GUI elements unique to the PyCrust application program Provides global signal dispatching services The document module contains a very simple Document...

How do I make a slider

Tkinter Slider

A slider is a widget that allows the user to select a number from within a range by dragging a marker across the width or height of the control. In wxPython, the control class is wx.Slider, which includes a read-only text display of the current value of the slider. Figure 7.7 displays examples of a vertical and horizontal slider. Basic slider use is fairly straightforward, but there are a number of events you can add. Figure 7.7 A vertical wx.Slider and a horizontal wx.Slider, which use the...

How do I make a nonrectangular frame

Wxpython Demo

In most applications, frames are rectangles because rectangles have a nice regular shape and are relatively simple for an application to draw and maintain. Sometimes, though, you need to break out of the straight line straitjacket. In wxPython, you can give a frame an arbitrary shape. If an alternate shape is defined, the parts of the frame that are outside the shape are not drawn, and do not respond to mouse events as far as the user is concerned, they are not part of the frame. Figure 8.9...

How do I add and update a status bar

In wxPython, you can add and place a status bar in the bottom of a frame by calling the frame's CreateStatusBar method. The status bar automatically resizes itself when the parent frame resizes. By default, the status bar is an instance of the class wx.StatusBar. To create a custom status bar subclass, attach it to your frame using the SetStatusBar method, with an instance of your new class as the argument. To display a single piece of text in your status bar, you can use the SetStatus-Text...