Table des matières

Guide de démarrage pour Boa Constructor

<term boa>Boa Constructor, un EDI/RAD pour Python</term> ;#; Kevin Gill
1 novembre 2000
mars 2005 mise à jour de Boa 0.4.0
juillet 2007 mise à jour de Boa 0.6.0
par Werner F. Bruhin ;#;

Une visite de l'environnement de développement Boa Constructor

Installation et démarrage de Boa Constructor

Boa s'exécute sur n'importe quelle plate-forme Windows 32 bits ou sur n'importe quelle plate-forme UNIX avec la boîte à outils de fenêtrage GTK+.

Installation sous Windows

UNIX Installation

You will now see the tools of the Boa Constructor development environment

This is divided into three sections/areas:

Installation from CVS

The Boa installation guide on the wxPython wiki page (http://wiki.wxpython.org/BoaInstallGuide) provides details on how to obtain Boa from CVS

The Palette Window

The Palette window is the main window of the Boa Constructor Program. Closing the Palette window will terminate the program. The Palette contains two sections, a toolbar, and a multi-pane notebook.

Palette Window

The toolbar gives access to the other windows in the Boa Constructor application. You can hold the mouse pointer over the different icons and help tips will appear. These help tips will tell you what the buttons do.

The notebook (or tabbed pane) provides a set of components which you can use while building your applications. The components are grouped for logical access.

The first group of components is called 'New'. This group provides components for creating new “files”, that can be a Python Application, a Python Module, a Setup file, a Boa Application or others.

In earlier versions there was also a tab for “Dialogs”, to insert the code for e.g. a file dialog you can now use the new “code template” feature. At the place in your code where you want the dialog press “Alt-t” and select from the drop down list.

wx.App Icon

The icon shown above is used to create a new Boa Application (its tool tip is wx.App, refering to the base class it uses). The new application consists of the application source file (App1.py) and the initial frame (Frame1.py).

The application file is used as the starting point for the application. The default new application simply loads the form. The form is a blank form. You can add components to this form.

Boa constuctor opens the source code for the new application and the new form in the Editor Window.

Toolbar Icons - Application

ToolBar Application Icons

Clicking the first one will bring the Inspector window to the foreground.
Clicking the second one will bring the Editor window to the foreground.
The check box will indicate that a compenent is selected and the text “Nothing selected” will be replaced with e.g. wx.Panel

Toolbar Icons - Help

Toolbar Help Icons

Clicking the first one will bring up Boa help or help for the selected component
Clicking the second one will bring up wxPython help
Clicking the third one will bring up Python help

The Editor Window

The Editor window is one of the three windows which is created when you run Boa Constructor. If you close the Editor Window, you can re-open it from the Palette Window using the Button.

When it is opened the Editor provides two pages, the Shell page and the Explorer page. You can now open a source file into the Editor. There are several methods for opening a source file in Boa Constructors editor.

Editor - source view

When a source file is opened, the editor creates a new page for the module. Within that page, the editor creates another notebook to provide alternative views of the file, this depends on the type of file. In this case we show an “App1” and “Frame1”, for the Frame1 file three views are shown, 'Source', 'Explore' and 'Events', should you look at the “App1” file you would see 'Application', 'Source' and 'Explore' views.

Note:

The “*” on the “App1” and “Frame1” tab indicate that changes have been made which are not saved.

The Source View (seen above) shows the source code and allows you to change the source code, unless it has a “blueish” background which indicates that the Frame Designer is open/active for this file.

Editor - Explore view The Explore View provides a tree view of the module and the icons shown indicate the following:

Icon - Class Classes
Icon - Method Methods
Icon - Function Functions
Icon - Event Events
Icon - Global Global

The 'Explore' Pane shows a Class based view of your source. The methods and attributes of each class in the source are displayed. You can double-click the mouse left button on an attribute or method, and the 'Source' view will display the definition/source code for that item.

Editor - Event view

The 'Events' Pane shows a Control based view of the Events you defined using Boa's Inspector. Manually added events outside the Boa generated code will not show here.

Additional views can be opened through the Editor/Views menu, this includes such views as “Application ToDo”, “Application Documentation”, “UML” etc, some views will only be available for certain file types.

The 'Views' menu in the editor provides other views on the source. These are Hierarchy, Documentation, ToDo, Application ToDo, Imports, UML, CVS conflicts, Readme.txt, Changes.txt, Todo.txt, Bugs.txt.

The icons available on the Editor window toolbar for a wxFrame file are:

The icons available on this toolbar change depending on the active file.

Editor toolbar - File icons The icons above allow you to open, close, save, save-as files and Browse forward/backward icons allow you to jump to marked possitions (CTRL-M).

Editor toolbar - Run icons The icons above let you run the application, run the module or debug the application.

Editor toolbar - source icons The icons above let you profile the module, check the source, or start the frame designer (sometimes also refered to as GUI Editor).

Editor toolbar - copypaste Icons The icons above let you Refresh the screen, Undo, Redo, Cut, Copy and Paste.

Editor toolbar - Search icons The icons above let you Find/Replace, Find again, and print the source.

Editor toolbar - Other icons The icons above let you run to the cursor (in debugger), toggle a breakpoint (you can also use F5), insert module information (Author name etc, this can be customized, see Module Info), and help.

Some helpfull short-cuts:

The Frame Designer Windows

You access the Frame Designer Window using the frame designer button on the Editor Window toolbar. The Frame Designer can only be started if the active file is a Form (wx.Panel, wx.Frame etc) or Dialog type file.

The Designer will display the frame on the screen. The Designer displays the frame as it would appear at runtime. This frame is referred to as the 'Designer'. The Designer also creates two new pages in the Editor. The first one is referred to as the Data View, the second one is the Sizer View.

The 'Designer' is used to design the layout of the Frame or Dialog. You can place components in the pane, resize them, move them or delete them. You can also place components within other components.

To create a component, you select the appropriate component from the Palette. Components are grouped for easier access, e.g. the basic controls are together. Once you have selected a control, the status bar in the Palette shows the selected control.

To place the component move the cursor onto the Designer. Click the mouse once in the position where the component is required. Once the component is on the form, it can be moved and resized. You move it by placing the mouse within the component and dragging it. You resize it by dragging one of the eight markers shown on the edge of a selected control.

Changes made through the Designer are saved into the applications source code. Changes are saved when you press the Post button There are two Post buttons, one on the Editor's toolbar and one on the Inspector's toolbar. Pressing either will close the Designer and the Data View and generate the source code for the changes. Changes can also be posted by closing the Frame.

To Cancel all changes made since opening the Designer, click the Cancel button on the Editor or Inspector toolbar.

Frame Designer

The Frame1 titled window above is the Frame Designer window, a wx.Panel (found on the Containers/Layout palette) has been placed in the wx.Frame and into it two wx.Button controls (found on the Buttons palette) have been placed. The button2 control is currently selected and you can see its properties shown in the Inspector window.

The controls on the Utilities(Data) tab you should drop onto the Data View tab and all sizer type containers (on Containers/Layout tab) you have to drop onto the Sizer View.

The Inspector Window

The Inspector always shows the configuration of the currently selected component. The Inspector contains 4 pages, the Constructor page ('Constr'), the Properties page ('Props'), the Events Page ('Evts') and the Objects Page ('Objs').

Inspector - ConstructorThe Constructor page allows you to edit properties which are required at object construction time, e.g. the name and style of the component.
Look at the wxPython help for the values passed to the constructor for a control. The styles in the manual are of particular importance.
Please note that changes to certain constructor parameters only take effect when the control is created.
You should change the “Name” property to something which will make sense to someone else or to you in 3 month time!
Inspector - PropertiesThe Properties page gives fine grained control to all properties for this component, e.g. fonts and colours.
Inspector - EventsThe Events page allows you to select the events which you wish to handle in your code. The events are grouped into logical groups.
Creating an event is easy, just click on e.g. “ButtonEvent” and click on “wx.EVT_BUTTON” and Boa will create an “OnButton” event called “OnControlNameButton”, obviously you will need to add to the generated source what actions you want to take when a user presses this button.
Inspector - ObjectsThe Objects page allows you to navigate through your components in an alternative format to the Designer pane. This is particularily useful if you have invisible or overlapping components. Also certain components like the wxStatusBar do not process click events (on MSW) so it has to be selected in the Objects page.

Managing the Application

When the module being edited is an application, the Editor provides a special Application View. This Application View allows you to easily track the files in your application, and to add new modules, dialogs and other types of files to your application.

While viewing an Application (any of its views) you may select an item from the 'New' pane in the Palette and it will be added to the Application.

Application

Editor Toolbar - app icons

The first of the above icons lets you add an existing file to this application.
The second one lets you remove a file from the application.

The Panel1 listed as a module above is NOT the same as the Panel1 contained in Frame1!

Getting around using Explorer

The second page of the Editor notebook contains a page called the Explorer. You use this page to browse various data sources including the filesystem, CVS, Zope, WebDAV, SSH accounts, FTP.

The Explorer shows filesystems and development directories from your operating systems. The first time Boa Constructor is run these filesystems and development directories are added. You can also re-configure where to look see Setting Preferences.

The python directories are taken from the environment variable PYTHONPATH, and the default locations as compiled into your Python runtime system.

Directories that you use a lot can be added to the Bookmarks section by selecting them and clicking on the Bookmark tool Editor Toolbar - Bookmark or by using the Edit menu or by right mouse clicking the Directory, note that this item will show next time you start Boa or after you select from the menu Edit/Reload.

If you are using Zope, you can access projects in your Zope Server using the Zope option. The default TCP/IP connection information is configured in the Inspector pane or in your Explorer configuration file, Explorer.msw.cfg on Windows or Explorer.gtk.cfg on UNIX.

Explorer

It also allows you to access your Preference settings, above the Key bindings are selected in the Explorer and details are shown in the Inspector.

The wxPython demo shows in the Explorer as it has been activated through the Plug-ins.

Using Help

The Boa Constructor environment provides links to different help files from your environment.

As of Boa 0.6.0 the following help files are included:

Additional help books can be added (see help books).

Help - Ctrl-H

The easiest and fastes access to help is just about anywhere in Boa via CTRL-H, then key in what you are looking for and Boa will find all references in ALL the helpbooks it knows about (e.g. wxPython, Python etc) and shows it in a display similar to below.

Help - Main

The help window provides standard HTML based navigation and a search facility.

If the help does not display correctly, you may need to configure your environment.

Other good places to look for help are:

Tutoriel - Création de notre première application

Cette section présente un bref tutoriel. Le but de ce tutoriel est de vous familiariser avec l'environnement de développement Boa. Ce tutoriel vous guide étape par étape à travers le processus de construction d'un simple éditeur de texte, appelé Notebook. Après avoir suivi ce tutoriel, vous en saurez pour être efficace avec Boa.

Vous apprendrez à :

Création d'une nouvelle application

Palette

Editor La vue ci-dessus montre dans l'éditeur les deux nouveaux fichiers créés et enregistrés.

Run Icons Un clic sur le bouton «Démarrer l'application» (jaune) montre le résultat de la «programmation», c'est à dire juste un cadre vide.

Utilisation de l'éditeur graphique pour définir le titre

Designer}}

Ajouter une barre d'état

Le premier composant que nous allons ajouter à l'application sera une barre d'état qui indiquera à l'utilisateur ce qui se passe quand le programme s'exécute, donnera des messages d'aide brefs ou d'autres informations.

Palette - Containers

Inspector - statusbar

Collection - statusbar

Inspector - Frame

Ajouter une barre de menus

Nous allons maintenant ajouter une barre de menus à l'application. Une barre de menus est un élément courant des programmes Windows. Notre barre de menu contiendra deux entrées, Fichier et Aide. La sélection d'un de ces menus affiche un menu déroulant. L'utilisateur peut sélectionner une option dans le menu déroulant.

Designer - Menu

Collection - About

Inspector - Event
  • Le côté gauche de la fenêtre des événements montre les groupes d'événements disponibles. Pour menuitem, il n'y a que le groupe 'MenuEvent'. Sélectionner ce groupe.
  • Le côté droit de la fenêtre d'événements affiche maintenant les événements dans le groupe sélectionné. Pour le menu, il n'y a qu'un seul événement EVT_MENU dans le groupe «MenuEvent». Double-cliquer sur cet événement.
  • Le bas du volet Événements affiche les gestionnaires d'événements dans l'application pour le composant actuel (l'item «A propos» du menu ). Il y a maintenant un nouveau gestionnaire appelé OnMenuHelpAboutMenu. C'est le nom de la méthode qui sera appelée lorsque l'option 'A propos' est sélectionnée dans le menu Aide.
  • Noter le nommage du gestionnaire d'événements. Boa génère les noms de cette manière. L'événement est la dernière partie (Menu). Le composant est la partie centrale (ici, 'A propos', sous-composante de la composante «menuHelp». Enfin, Boa respecte la convention de préfixer tous les gestionnaires d'événements avec le mot 'On'.
  • Fermer l'éditeur de collection.

Maintenant, nous devons répéter le processus pour ajouter des options dans le menu fichier.

Maintenant, nous allons créer la barre de menus.

Inspector - Frame

Frame1

Ajout du contrôle texte

La tâche suivante consiste à ajouter du texte principal contrôle d'édition à notre cadre. Ce contrôle s'appelle wx.TextCtrl.

Survoler chaque commande pour connaître son nom.

Utiliser Ctrl+H et entrer 'textctrl' pour obtenir de la documentation et des descriptions des différents styles, noter que certains peuvent ne pas être montrés pour wx.TextCtrl car ils sont hérités, par exemple wx.Window.

Inspector - TextCtrl

TextEditor

Ajout des fonctionnalités du Menu Fichier

La tâche suivante consiste à interagir avec l'utilisateur pour implémenter les fonctionnalités des menu. Des boîtes de dialogue sont utilisées pour saisir l'entrée de l'utilisateur. Ces boîtes de dialogue sont modales, c'est à dire qu'on ne pas utiliser les autres fenêtres de l'application en cours jusqu'à ce que le dialogue soit fermé.

def OnMenuFileOpenMenu(self, event):
  dlg = wx.FileDialog(self, "Choose a file", ".", "", "*.*", wx.OPEN)
  try:
    if dlg.ShowModal() == wx.ID_OK:
      filename = dlg.GetPath()
      # Your code
  finally:
    dlg.Destroy()
  event.Skip()
def OnMenuFileOpenMenu(self, event):
  dlg = wx.FileDialog(self, "Choose a file", ".", "", "*.*", wx.OPEN)
  try:
    if dlg.ShowModal() == wx.ID_OK:
      filename = dlg.GetPath()
      # Your code
      self.textEditor.LoadFile(filename)
      self.FileName=filename
      self.SetTitle(('Notebook - %s') % filename)        
  finally:
    dlg.Destroy()
def OnMenuFileSaveasMenu(self, event):
    dlg = wx.FileDialog(self, "Save file as", ".", "", "*.*", wx.SAVE)
    try:
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()
            # Your code
            self.textEditor.SaveFile(filename)
            self.FileName=filename
            self.SetTitle(('Notebook - %s') % filename)     
    finally:
        dlg.Destroy()
def OnMenuFileCloseMenu(self, event):
    self.FileName = None
    self.textEditor.Clear()
    self.SetTitle('Notebook')
def OnMenuFileExitMenu(self, event):
        self.Close()
def __init__(self, parent):
    self._init_ctrls(parent)
    self.FileName=None
def OnMenuFileSaveMenu(self, event):
    if self.FileName == None:
        return self.OnFileSaveasMenu(event)
    else:
        self.textEditor.SaveFile(self.FileName)

Editor

Créer une fenêtre de dialogue

Les boîtes de dialogue permettent d'interagir avec l'utilisateur et de récupérer les valeurs entrées. Précédemment, nous avons utilisé la boîte de dialogue pré-construite wx.FileDialog ; nous allons maintenant développer notre propre boîte de dialogue pour l'option de menu A propos.

Lancer l'application. Le nouveau dialogue devrait ressembler à ceci :

About Dialog

Félicitations: Vous avez construit votre première application en utilisant Boa constructeur. Votre éditeur est terminé. Dans ce tutoriel, vous avez utilisé les composants de base de Boa.

Prenez le temps de revoir ce que vous avez fait jusqu'ici. Vous avez appris à :

Creating an application window using sizers

Sizers are a great way to ensure that your GUI layout is nice and clean. They come in especially handy when you do not know exactly how much space a control needs and/or should be allowed to use, this can be the case when you internationalize your application (I18N) or for such controls as lists or grids where you like to give as much space as possible to them (or maybe as little as practical).

Please note that the following will just explain how to use sizers in Boa (note that this assumes version 0.6.x of Boa). For more detailed information about sizers you should check the wxPython documentation, the wxPython demo and you might also find the following links helpful (if not a must!) to understand sizers.

We will use a wx.Frame and create a screen for address information entry.

Designer and Collection Editor

Address entry form 1

Address entry form

Address form final

Please note that the file generated during this example is also available in the directory “Examples\guide” under your Boa installation directory.

For coding guide lines you might also want to consult the wxPython style guide http://wiki.wxpython.org/index.cgi/wxPython_Style_Guide.

Other Useful Items

Setting Preferences

The Boa Constructor tool provides a number of features which can be customised by you.

Most of the customization settings can be set by using the Editor Explorer View. Click on Preferences and it shows you something similar to the image below.

Preferences

To change settings double click on either 'General', 'Platform specific' or 'Key bindings' and the properties of each will be shown in the Inspector as shown below:

General Platform Key bindings

Help books

Boa by default includs its help books and the ones for wxPython and Python.

However if you like to add others you can do so by selecting Preferences/Help Books and right mouse click in the right pane of the Explorer. Select 'Add new Item' and browse to find the '.hpp' file.

Help book

Bookmarks

If you like to add additional bookmarks just right mouse click on the folder you like to add within the Explorer.

Transport

Adding additional transports works similar to the bookmarks, select the transport type on the left hand side of the Explorer view, e.g. 'Zope' and then right mouse click in the right hand side and select 'New' and then complete the information in the Inspector.

Transport

Module Info

You might want to change the following section in the file 'prefs.rc' stored in your user preference directory, on a Windows system this is by default in 'driveletter:\Documents and Settings\username\.boa-constructor'.

# Info that will be filled into the comment block. (Edit->Add module info)
# Also used by setup.py
staticInfoPrefs = { 'Purpose':   '',
                    'Author':    '<your name>',
                    'Copyright': '(c) 2004',
                    'Licence':   '<your licence>',
                    'Email':     '<your email>',
                  }

If you like to edit the 'CustomModuleInfo.plug-in' file right mouse clicking the corresponding entry in 'Preferences/Plug-ins/Plug-in files' and select 'Open Plug-in file'.

If you don't want to loose your changes when you upgrade Boa you might want to copy the 'CustomModuleInfo.plug-in' file and call it 'MyCustomModuleInfo.plug-in' in the Plug-ins directory. After restarting Boa you should disable the standard one by right mouse clicking and selecting the appropriate option.

I changed it as follows:

""" Demonstrates how to change system constants as a plug-in """

import sourceconst
# The order of (Name)s may change and lines may also be removed
sourceconst.defInfoBlock = '''# -*- coding: iso-8859-1 -*-#
#-----------------------------------------------------------------------------
# Name:        %(Name)s
# Purpose:     %(Purpose)s
#
# Author:      %(Author)s
#
# Created:     %(Created)s
# RCS-ID:      %(RCS-ID)s
# Copyright:   %(Copyright)s
# Licence:     %(Licence)s
#-----------------------------------------------------------------------------
'''

import Preferences
# (Name)s not in the original dictionary needs to be added
# New field:   %(NewField)s
#Preferences.staticInfoPrefs['NewField'] = 'Whatever'

After restarting Boa and clicking on the button Module Info Boa will insert the following into the selected file (in this case Frame1.py).

# -*- coding: iso-8859-1 -*-#
#-----------------------------------------------------------------------------
# Name:        Frame1.py
# Purpose:    
#
# Author:      Werner F. Bruhin
#
# Created:     2005/12/03
# RCS-ID:      $Id: node31.html,v 1.1.2.1 2005/03/14 09:23:09 wbruhin Exp $
# Copyright:   (c) 2004 - 2005
# Licence:     Shareware, see license.txt for details
#-----------------------------------------------------------------------------
1)
On peut ajouter plusieurs champs