Private and public variables and methods

Unless you take special action, all variables and methods are public and virtual. If you make use of name mangling, however, you can emulate private variables and methods. You mangle the name this way Any name which begins with a double-underscore _ is private and is not exported to a containing environment. Any name which begins with a single underscore _ indicates private by convention, which is similar to protected in C or Java. In fact, Python usually is more intuitive than C or other...

contents

preface xv special thanks xvii about the reader xix about the author xx conventions xxi about the cover xxii author online xxiii 1.1 Introduction to Python programming and a feature review 3 Why Python 4, Where can Python be used 5 1.2 Key data types lists, tuples and dictionaries 5 Lists 5, Tuples 7, Dictionaries 8 How do classes describe objects 9, Defining classes 9, Neat Python trick 10 9, Initializing an instance 10, Methods 10, Private and public variables and methods 11, Inheritance 11,...

Options specific to Canvas

closeenough Specifies a floating-point value indicating how float 0.5 close the mouse cursor must be to an item before it is considered to be inside the item. Defaults to 1.0. confine Specifies a boolean value that indicates whether or not it should be allowable to set the canvas's view outside the region defined by the scrollre-gion argument. Defaults to true, which means that the view will be constrained within the scroll region. Specifies the color to use as background in the color 'yel-...

Distributing Unix applications

Supporting your application is usually a simple task once you have access to a built Python and Tcl Tk. In general, UNIX end users are capable of building and installing both of these so you may be able to simply require your end users to take care of them. Then your application installation may be as simple as extracting files from a tar file and editing the users' environments appropriately. For the moment, let's assume that this is the case, so we will concentrate on getting your application...

Human factors

Extensive documents on Human Factor Engineering describe GUI design in scientific terms see the Reference section . In particular, font choice may be based on calculating the arc subtended by a character from a point 20 inches from the character the viewing position . While I have worked on projects where it was necessary to actually measure these angles to confirm compliance with specifications, it is not usually necessary to be so precise. When designing an application that includes a GUI,...

Idle

Screenshot Idle Python

IDLE is an emerging IDE for Python. It has some limitations which will reduce as time goes by and its usage increases. You can already see demands for various types of functionality on the Python news group. This will continue to grow as more users find out what is needed in the tool. Make sure that you obtain the latest code rather than using the code packaged in Python 1.5.2 many changes and bug fixes have been made recently. I have included a screenshot of an IDLE session to give you an idea...

NumPy

NumPy is a nickname for a package of Numerical Extensions to Python. These extensions add two powerful new types to Python a new sequence type which implements multidimensional arrays efficiently multiarray and a new type of function called a universal function ufunc which works efficiently on the new arrays and other sequence types. These new objects give Python the number-crunching power of numeric languages like MATLAB and IDL while maintaining all of the advantages which Python has as a...

Using hierarchical packing

While it is relatively easy to use the Packer to lay out simple screens, it is usually necessary to apply a hierarchical approach and employ a design which packs groups of widgets within frames and then packs these frames either alongside one other or inside other frames. This allows much more control over the layout, particularly if there is a need to fill and expand the widgets. Figure 5.15 illustrates the result of attempting to lay out two columns of widgets. At first glance, the code...

Visibility methods

Window managers usually provide the ability to iconify windows so that the user can declut-ter the workspace. It is often appropriate to change the state of the window under program control. For example, if the user requests a window which is currently iconified, we can deiconify the window on his behalf. For reasons which will be explained in Programming for performance on page 348, it is usually better to draw complex GUIs with the window hidden this results in faster window-creation speeds....

Some finishing touches

Tkinter Menubar Options

We are going to extend the capability of draw3.py to add some additional functionality and provide some features that may be useful if you use this example as a template for your own code. This is what has been added 1 Menu options to create New drawings and Open existing ones. 2 A Menu option to save drawings with a supplied filename Save As . 3 A Menu option to save an existing drawing to its file Save . 4 A Move operation to allow an object to be moved about the canvas. 5 Stretch operations...

X Window System font descriptors

Of course, the older font descriptors are available if you really want to use them. Most X Window fonts have a 14-field name in the form Normally, we only care about a few of the fields These fields are defined as follows family A string that identifies the basic typographic style for example, helvetica, arial, etc. . weight A string that identifies the nominal blackness of the font, according to the foundry's judgment for example, medium, bold, etc. . slant A code string that indicates the...

Browsers

Browsers have become a popular motif for navigating information that is, or can be, organized as a hierarchy. Good examples of browsers include the Preferences editor in Netscape and Windows Explorer. The advantage of browsers is that branches of the typical tree display can be expanded and collapsed, resulting in an uncluttered display, even though the volume of data displayed can be quite high. As an example, we are going to develop a simple image browser which will display all of the images...

The Menubutton widget

Table A.57 Menubutton widget standard options -activebackground color -activeforeground color -anchor anchorPos -background color -bitmap bitmap -borderwidth width -cursor cursor -disabledforeground color -font font -foreground color -height height -highlightbackground color -highlightcolor color -highlightthickness width -image image -justify left center right -padx width -pady height -relief flat groove raised ridge sunken -state normal disabled active -takefocus focusType relief FLAT GROOVE...

Screen layout

5.1 Introduction to layout 77 5.4 Placer 90 5.2 Packer 79 5.5 Summary 94 GUI layout is an often-misunderstood area a programmer could conceivably waste a lot of time on it. In this chapter, the three geometry managers, Pack, Grid and Place are covered in detail. Some advanced topics, including approaches to variable-size windows and the attendant problems of maintaining visually attractive and effective interfaces, will be presented.

ButtonBox options

If the labelpos option is not None, this specifies the dis- distance tance between the label component and the rest of the mega- Specifies where to place the label component. If not None, it anchor should be a concatenation of one or two of the letters N, S, E and W. The first letter specifies on which side of the megawid-get to place the label. If a second letter is specified, it indicates where on that side to place the label. For example, if labelpos is W, the label is placed in the center...

A standard application framework

One of the problems with designing forms is that some features are common to most applications. What we need is a standard application framework which can be adapted to each application this should result in moderate code reuse. Many applications fit the general form shown in figure 8.7. In addition, we need the ability to provide busy cursors , attach balloon help and help messages to fields, supply an about message and add buttons with appropriate callbacks. To support these needs, I'll...

EntryField options

This specifies a function to call whenever the Return key is function None pressed or invoke is called. Specifies the background color to use when displaying invalid or partially valid text. This is a dictionary of extra validators. The keys are the names of validators which may be used in a future call to the validate option. Each value in the dictionary is a tuple of validate_function, stringtovalue_function . The validate_function is used to implement the validation and the...

Other Tk commands

clipboard append -displayof win -format fmt -type type data window.clipbord_clear data , option value window.option_add pattern, value, , priority window.option clear window.option_get name, class Table A.86 Other Tk methods continued window.option_readfile fileName , priority selection clear -displayof window -selection selection , selection sel selection get -displayof window -selection selection -type type , -selection sel , type type selection handle -selection sel -type type -format fmt...

Drawing blobs and rubber lines

10.2 A more complete drawing program 244 10.5 Stretching canvas objects 258 10.6 Some finishing touches 262 Despite the title, this chapter covers some of the techniques used to build drawing tools and interfaces which allow the user to create and move objects around in a GUI. The chapter is not meant to be a complete guide to developing a new paint tool, but I will provide you with some useful templates for drawing objects on a canvas, using rubber lines and rearranging objects on a canvas....

Timers and background procedures

The mainloop supports callbacks which are not generated from events. The most important result of this is that it is easy to set up timers which call callbacks after a predetermined delay or whenever the GUI is idle. Here is a code snippet from an example later in the book self.frame.after self.blinkrate 1000, self.update self.canvas.update_idletasks if self.blink self.frame.after self.blinkrate 1000, self.update This code sets up to call self.update after self.blinkrate 1000 milliseconds. The...

Distributing Tkinter applications

19.1 General issues in distributing 19.3 Distributing Win32 applications 374 applications 376 19.2 Distributing Unix applications 375 19.4 Python distribution tools 379 If you follow the Python news group for a few weeks, you will see at least one question being raised repeatedly How do I distribute Python applications . In this chapter we will look at some options for UNIX and Win32. UNIX is relatively easy to handle, but Win32 has several possible solutions.

Checkbutton

Checkbutton widgets are used to provide on off selections for one or more items. Unlike radiobuttons see Radiobutton on page 37 there is no interaction between checkbuttons. You may load checkbuttons with either text or images. Checkbuttons should normally have a variable intVar assigned to the variable option which allows you to determine the state of the checkbutton. In addition or alternately you may bind a callback to the button which will be called whenever the button is pressed. Note that...

Dialogs and forms

.1 Dialogs 141 8.5 Browsers 175 .2 A standard application 8.6 Wizards 184 framework 155 8.7 Image maps 191 .3 Data dictionaries 165 8.8 Summary 198 .4 Notebooks 172 This chapter presents examples of a wide range of designs for dialogs and forms. If you are not in the business of designing and developing forms for data entry, you could possibly expend a lot of extra energy. It's not that this subject is difficult, but as you will see in Designing effective graphics applications on page 338,...

Options shared by many widgets

Specifies the background color to use color when drawing active elements. An element a widget or portion of a widget is active if the mouse cursor is positioned over the element and pressing a mouse button will cause some action to occur. If strict Motif compliance has been requested by setting the tk_strictMotif variable, this option will normally be ignored the normal background color will be used instead. For some elements on Windows and Macintosh systems, the active color will only be used...

Pmw Megawidget tour

Python megawidgets, Pmw, are composite widgets written entirely in Python using Tkinter widgets as base classes. They provide a convenient way to add functionality to an application without the need to write a lot of code. In particular, the ComboBox is a useful widget, along with the Entry field with several built-in validation schemes. In a similar fashion to the Tkinter tour, above, the following displays show typical Pmw widget appearance and usage. The code is kept short and it illustrates...

What is a window manager

If you already know the answer to that question, you may want to skip ahead. It is perfectly possible to develop complex GUI-based applications without knowing anything about the window manager. However, many of the attributes of the displayed GUI are determined by the window manager. Window managers exist in one form or another for each of the operating systems examples are mwm Motif , dtwm CDE and ovwm OpenView . In the case of Win32, the window manager is just part of the operating system...

Implementing the front panel

Some preparation work needs to be done to convert the notional front panel to a working system. In particular, it is necessary to calculate the sizes of screen components based on some scaling factors, since the majority of panels are much larger than typical computer screens. As the reader will observe in the following example code, the author tends to work with relative positioning on a canvas. This is a somewhat more difficult approach to widget placement J connectors are typically used for...

Keyboard navigation mouseless navigation

It is easy to forget to provide alternate navigation methods. If you, as the programmer, are used to using the mouse to direct focus, you may overlook mouseless navigation. However, there are times when the ability to use Tab or Arrow keys to get around a GUI are important. There may be times when the mouse is unavailable I've had problems with a cat sleeping on my desk and leaving mouse-jamming hairs or when an application is intended to be deployed in a hostile environment where a mouse just...

T

tabcanvas 583 tabcolor 582 tabheight 582 tabpos 578 tabs 531 tag 565 466, 535 tag_cget 535 tag_config 26 tag_configure 535 tag_delete 536 tag_lower 466, 536 tag_names 536 tag_nextrange 536 tag_prevrange 536 tag_raise 467, 537 tag_ranges 537 tag_remove 537 tag_unbind 467, 537 tagbind 546 tagindentl 564 tags 249, 469, 470, 471, 474, 475, 476, 478, 479, 480 tagunbind 546 takefocus 98, 100, 233, 302, binary distribution 611 converting to Tkinter 237 environment variables 613 library 13 source...

scaletagOrId xOrigin yOrigin xSc

Rescale all of the items given by tagOrId in canvas coordinate space. XOrigin and yOrigin identify the origin for the scaling operation and xScale and yScale identify the scale factors for x- and y-coordinates, respectively a scale factor of 1.0 implies no change to that coordinate . For each of the points defining each item, the x-coordinate is adjusted to change the distance from xOrigin by a factor of xScale. Similarly, each y-coordinate is adjusted to change the distance from yOrigin by a...

The Toplevel widget

Table A.70 Toplevel widget standard options -relief flat groove raised ridge sunken relief FLAT GROOVE RAISED RIDGE SUNKEN SOLID Table A.71 Toplevel widget-specific options -background color -class string -colormap colormap -container boolean -menu pathName -use windowID -screen screen -visual visual

Events

We express events as strings, using the following format lt modifier-type-qualifier gt modifier is optional and may be repeated, separated by spaces or a dash. type is optional if there is a qualifier. qualifier is either a button-option or a keysym and is optional if type is present. Many events can be described using just type, so the modifier and qualifier may be left out. The type defines the class of event that is to be bound in X terms it defines the event mask . Many events may be...

iconmaskbitmapNone

If bitmap is specified, then it names a bitmap in the standard forms accepted by Tkinter Tk_GetBitmap . This bitmap is passed to the window manager to be used as a mask in conjunction with the iconbitmap option where the mask has zeroes no icon will be displayed where it has ones, the bits from the icon bitmap will be displayed. If bitmap is not specified, then any current icon mask is cancelled for window this is equivalent to specifying a bitmap of all ones . If bitmap is specified then the...

Wizards

Windows 95 98 NT users have become familiar with wizard interfaces since they have become prevalent with installation and configuration tools. Wizards guide the user through a sequence of steps, and they allow forward and backward navigation. In many respects they are similar to Notebooks, except for their ordered access as opposed to the random access of the Notebook. This example illustrates a wizard that supports software installation. WizardShell.py is derived from AppShell.py, but it has...

defineoptionskeywords optionDefs

Creates options for this megawidget. The optionDefs argument defines the options. It is a sequence of 3-element tuples, name, default, callback , where name is the name of the option, default is its default value and callback is the function to call when the value of the option is set by a call to configure . The keywords argument should be the keyword arguments passed in to the constructor of a megawidget. The user may override the default value of an option by supplying a keyword argument to...

Building an application

3.1 Calculator example key features 21 3.2 Calculator example source code 21 3.3 Examining the application structure 27 3.4 Extending the application 28 Most books on programming languages have followed Kernigan and Ritchie's example and have presented the obligatory Hello World example to illustrate the ease with which that language may be applied. Books with a GUI component seem to continue this tradition and present a Hello GUI World or something similar. Indeed, the three-line example...

AboutDialog options

If this is callable, it will be called whenever the mega-widget is activated by a call to activate . Sets the application name displayed by AboutDialog. Specifies the width of the border to the left and right of the message area. Specifies the height of the border to the top and bot- distance tom of the message area. Specifies on which side of the dialog window to place the button box. Must be one of N, S, E, or W. This must be a tuple or a list. It specifies the names on the buttons in the...

RadioSelect options

buttontype Specifies the default type of buttons created by the add method. If button, the default type is Button. If radiobutton, the default type is Radiobutton. If checkbutton, the default type is Checkbutton. command Specifies a function to call when one of the buttons is clicked labelmargin If the labelpos option is not None, this specifies the distance between the label component and the rest of the mega-widget. labelpos Specifies where to place the label component. If not None, it should...

Creating a Light Emitting Diode class

The following example introduces an LED class to define Light Emitting Diode objects. These objects have status attributes of on, off, warn and alarm corresponding to typical net work management alarm levels along with the blink on off state, which may be selected at instantiation. The LED class also defines the methods to set the status and blink state at runtime. Figure 7.1 demonstrates the wide range of LED formats that can be generated from this simple class. Color.PANEL Color.OFF Color.ON...

Calculator example key features

The calculator example illustrates many features of applications written in Python and GUI application structure Although this is a simple example, it contains many of the elements of larger applications that will be presented later in the book. Multiple inheritance It is simple in this example, but it illustrates how it may be used to simplify Python code. Lists, dictionaries and tuples As mentioned in chapter 1, these language facilities give Python a considerable edge in building concise...

overrideredirectbooleanNone

If boolean is specified, it must have a proper boolean form and the override-redirect flag for window is set to that value. If boolean is not specified then TRUE or FALSE is returned to indicate whether the override-redirect flag is currently set for window. Setting the override-redirect flag for a window causes it to be ignored by the window manager among other things, this means that the window will not be reparented from the root window into a decorative frame and the user will not be able...

Inheritance

The rules of inheritance in Python are really quite simple Classes inherit behavior from the classes specified in their header and from any classes above these classes. Instances inherit behavior from the class from which they are created and from all the classes above this class. When Python searches for a reference it searches in the immediate namespace the instance and then in each of the higher namespaces. The first occurrence of the reference is used this means that a class can easily...

Shared options Vuv

Insert the slave so that it occupies the nth column in the grid. Column numbers start with 0. If this option is not supplied, then the slave is arranged just to the right of previous slave specified on this call to grid, or column 0 if it is the first slave. For each x that immediately precedes the slave, the column position is incremented by one. Thus the x represents a blank column for this row in the grid. Insert the slave so that it occupies n columns in the grid. Insert the slave s in the...

Data dictionaries

The forms that I have presented as examples have been coded explicitly for the material to be displayed this becomes cumbersome when several forms are required to support an application. The solution is to use a data dictionary which defines fields, labels, widget types and other information. In addition, it may provide translation from database to screen and back to database, and define validation requirements, editable status and other behavior. We will see some more complete examples in...

NoteBook options

The width of the border drawn around each tab and around the integer 2 selected page. Specifies a function to call when a page is selected for the first function None time. The function is called with a single argument, which is the name of the selected page, and it is called before the raisecommand function. This allows the creation of the page contents to be deferred until the page is first displayed. Specifies a function to call when the selected page is replaced function None with a new...

Graphs and charts

There was a time when the term graphics included graphs this chapter reintroduces this meaning. Although graphs, histograms and pie charts may not be appropriate for all applications, they do provide a useful means of conveying a large amount of information to the viewer. Examples will include linegraphs, histograms, and pie charts to support classical graphical formats. More complex graph examples will include threshold alarms and indicators.

Miscellaneous wm methods

There are several window manager methods, many of which you may never need to look at. They are documented in Inherited methods on page 433. However, you might find a few of them useful. To raise or lower a window in the window stack, use lift and lower you cannot use raise since that is a Python keyword self.top.lift Bring to top of stack self.top.lift name Lift on top of 'name' self.top.lower self.spam Lower just below self.spam To find which screen your window is on this is really only...

Grid

Many programmers consider the Grid geometry manager the easiest manager to use. Personally, I don't completely agree, but you will be the final judge. Take a look at figure 5.17. This is a fairly complex layout task to support an image editor which uses a by example motif. Laying this out using the Packer requires a hierarchical approach with several nested Frames to enclose the target widgets. It also requires careful calculation of padding and other factors to achieve the final layout. It is...

Threads and asynchronous techniques

18.2 after processing 369 Applications frequently have a need to process actions as parallel tasks or to perform time-consuming operations. This chapter covers threads and other techniques that support background processing. This area of programming for Python and Tkinter poses special problems that must be solved to prevent system hangs and unexpected behavior. It is also a difficult area to debug, since problems usually occur when the system is running at full speed, outside of any debugger...

special thanks

Writing Python and Tkinter Programming has been the collective effort of many people. Each of these persons contributed their time, expertise and effort to help make the book more effective. Many of the words are theirs and not mine the book is now better. I want to thank the team of technical reviewers Fred L. Drake, Robin Friedrich, Alan Gauld, Bob Gibson, Lynn Grande, Doug Hellmann, Garrett G. Hodgson, Paul Kendrew, Andrew M. Kuchling, Cameron Laird, Gregory A. Landrum, Ivan Van Laningham,...