Brief contents

Preface xv special thanks xvii about the reader xix about the author xx conventions xxi about the cover xxii author online xxiii 6 Events, bindings and callbacks 95 7 Using classes, composites and special widgets 120 10 Drawing blobs and rubber lines 237 Part 3 Putting it all together 311 16 Designing effective graphics applications 338 17 Programming for performance 348 18 Threads and asynchronous techniques 361 19 Distributing Tkinter applications 374 appendix A Mapping Tk to Tkinter 383...

Building a front panel

Let's construct a hypothetical piece of equipment. The task is to present a front-panel display of a switching system (perhaps an ATM switch or a router) to an administrator. The display will show the current state of the interfaces, line cards, processors and other components. For the purposes of the example, we shall assume that the device is SNMP-capable and that the code to poll the devices agent and to receive and process traps will be developed independently from the GUI. If this were not...

Building and installing Python Tkinter

In general, you will not need to build Python or its components from source binary distributions are readily available from www.python.org for several Unix variants, Win32, and MacOS. However, if you intend to build extensions to Python you will need to obtain the sources for Python and sometimes for Tcl and Tk. If you do decide to build Python, you may also want to build Tcl Tk. The information presented here is for Python 1.5.2 and Tcl Tk 8.0.5, which were the stable releases at the time of...

Counter Dialog

The CounterDialog widget provides a convenience dialog requesting the user to select a value from a Counter widget. The counter can contain any data type that the widget is capable of cycling through, such as the unlikely sequence shown in figure 4.29. Figure 4.29 Pmw CounterDialog widget label_text 'Enter the number of twits (2 to 8) n', counter_labelpos N, entryfield_value 2, counter_datatype 'numeric', entryfield_validate 'validator' 'numeric', 'min' buttons ('OK', 'Cancel'), defaultbutton...

Distributing Win applications

I think that this is much more problematic when compared to the UNIX case. You have several alternatives. I will advocate the simplest case, since the others do require interaction with the registry, which really implies that you will use an installation tool such as InstallShield, which automates the process of installing and registering the application components. More important, it perhaps makes provisions to install an uninstaller which removes the registry information and the installed...

Events bindings and callbacks

6.1 Event-driven systems a review 95 6.5 Binding events and callbacks 104 6.6 Timers and background procedures 107 6.7 Dynamic callback handlers 107 GUI applications rely heavily on events and binding callbacks to these events in order to attach functionality to widgets. I anticipate that many readers may have some familiarity with this topic. However, this may be a new area for some of you, so I will go into some detail to make sure that the subject has been fully covered. Advanced topics will...

Message Bar options

Labelmargin If the labelpos option is not None, this specifies the distance distance 0 between the label component and the rest of the megawidget. labelpos Specifies where to place the label component. If not None, it anchor None 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 megawidget 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...

Obtaining source distributions

Before collecting any source, decide where you are going to store the source files. You are going to have three directories (Python, Tcl and Tk) each with their revision as a suffix. You must arrange for these directories to be at the same relative level on the disk (for example, all in python_source). Next, visit www.python.org and find the latest version of Python (you will usually find a reference to the current version in the Topics panel). This should point you to the source distribution...

Options specific to Listbox

Default exportselection Specifies whether or not a selection in the widget boolean 0 YES 1 should also be the X selection. The value may have any of the forms accepted by Tcl_GetBoolean, such as true, false, 0, 1, yes, or no. If the selection is exported, then selecting in the widget deselects the current X selection, selecting outside the widget deselects any widget selection, and the widget will respond to selection retrieval requests when it has a selection. The default is usually for...

Options specific to Scale

Bigincrement Some interactions with the scale widget cause integer 60 its value to change by large increments this option specifies the size of the large increments. If specified as 0, the large increments default to 1 10 the range of the scale. digits An integer specifying how many significant dig- integer 2 its should be retained when converting the value of a scale widget to a string. If the number is less than or equal to zero, then the scale picks the smallest value that guarantees that...

S

Sans serif font 340, 343 Scale 46, 109, 110, 522 bigincrement 523 coords 524 digits 523 from 523 get 524 identify 525 label 523 length 523 orient 523 repeatdelay 523 repeatinterval 524 resolution 524 set 525 shared options 522 showvalue 524 sliderlength 524 sliderrelief 524 tickinterval 524 to 524 troughcolor 524 variable 524 scale 465 Scale widget 412 Scale widget methods 414 Scale widget standard options 413 scaling images 90 scan_dragto 252, 253, 465, 487, 500, 534 scan_mark 252, 253, 465,...

V

Validate 112, 115, 561 validating input 111 validation 107, 111, 116 date 113, 117 defining requirements 165 errors 113 IP address 114, 117 social security number 113 Social Security numbers 117 telephone numbers 117 times 117 validation error 113 validation function return values 560 validator 112, 115, 561 value 521, 561, 607 value changed callback 150 widget (continued) slave 78, 79 smart 117 smart widget 340 special 120 Text 528 textvariable 152 Toplevel 539 tree 181 validation 107 variable...

Placer

The Placer geometry manager is the simplest of the available managers in Tkinter. It is considered difficult to use by some programmers, because it allows precise positioning of widgets within, or relative to, a window. You will find quite a few examples of its use in this book so I could take advantage of this precision. Look ahead to figure 9.5 on page 213 to see an example of a GUI that would be fairly difficult to implement using pack or grid. Because we will see so many examples, I am only...

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

Screenshot Idle Python

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

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

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

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

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

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

Implementing the front panel

Tkinter Ugly

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

Wizards

Tkinter Clickable Canvas

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

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

Grid

Password Gui Tkinter Python

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

Calculator example source code

Python Codes Tkinter

Import Pmw O Python MegaWidgets SLabe1 defines a 2-sided 1abe1 within a Frame. The 1eft hand 1abe1 has b1ue 1etters the right has white 1etters. def _init_ se1f, master, 1eft1, right1 Frame._init_ se1f, master, bg 'gray40' se1f.pack side LEFT, expand YES, fi11 BOTH Labe1 se1f, text 1eft1, fg 'stee1b1ue1', font aria1, 6, bo1d , width 5, bg 'gray40' .pack side LEFT, expand YES, fi11 BOTH Labe1 se1f, text right1, fg 'white', font Maria1, 6, Mbo1d , width 1, bg 'gray40' .pack def _init_ self,...

The Button widget

Table A.48 Button widget standard options Table A.48 Button widget standard options -relief flat groove raised ridge sunken relief FLAT GROOVE RAISED RIDGE SUNKEN SOLID Table A.49 Button widget-specific options Table A.51 Checkbutton widget standard options -relief flat groove raised ridge sunken Table A.52 Checkbutton widget-specific options -indicatoron boolean -offvalue value -onvalue value -selectcolor color -selectimage image -variable variable checkbutton deselect checkbutton flash...

A simple example

Tkinter Examples Python

Many of the examples in this book use try except clauses to trap errors in execution. This is a good way of writing solid code, but it can make life difficult for the programmer if there are errors, since an error will cause Python to branch to the except section when an error occurs, possibly masking the real problem. Python has one downside to testing a program even though the syntax may be correct when Python compiles to bytecode, it may not be correct at runtime. Hence we need to locate and...

Note Book

Pmw Panedwidget

Release 0.8.3 of Pmw replaces NoteBookR and NoteBookS with Notebook. While it is quite similar to the previous notebooks, there are some small changes. In fact, you will have to make changes to your code to use NoteBook with existing code. However, the changes are minor and the new form may be a little easier to use. Figure 4.39 illustrates the new widget. Figure 4.39 Pmw NoteBook widget version 0.8.3 nb Pmw.NoteBook root p1 nb.add 'Page 1' p2 nb.add 'Page 2' p3 nb.add 'Page 3' nb.pack padx 5,...

The window manager

Wm aspect window minNumer minDenom maxNumer maxDenom wm colormapwindows window windowList wm focusmodel window active passive wm grid window baseWidth baseHeight widthInc heightInc wm overrideredirect window boolean wm positionfrom window program user wm resizable window widthBoolean heightBoolean window. wm_aspect minNumer, minDenom, maxNumer, maxDenom window. wm_colormapwindows windowList window. wm_focusmodel 'active' lpassivel window. wm_grid baseWidth, baseHeight, widthInc, heightInc...

After processing

The after method has been used frequently in examples, including the threading examples above, to provide simple alarm callbacks. For X window programmers, after is similar to XtAppAddTimeOut. after_idle is similar to XtAppAddWorkProc, which provides a simple mechanism to define a background task which is executed when there are no events in the event queue with the exception of pending after events . Here is a simple example which illustrates using after_idle to implement a busy cursor which...

Drawing on a canvas

Python Tkinter Canvas Example

We have already encountered several examples of objects drawn on canvases. However, these objects were drawn to represent physical objects on front panels and to create images pro-grammatically. Now we need to allow the user to create drawn objects on the canvas. Almost all drawing operations define a bounding box which encloses the object. The bounding box is expressed as a pair of x y coordinates at the top-left and bottom-right corners. Lines are special cases they have a start and end...

Scrolled canvases

Many Canvas One Window Tkinter

Frequently, the size of a drawing exceeds the available space on the screen. To provide a larger canvas, we must scroll the canvas under a viewing area. Handling scrollbars in some windowing systems X Window, for example can require a moderate amount of code. Tkinter Tk makes scroll operations relatively easy to code. Take a look at this example, which was reworked directly from a Tk example. This window displays a canvas widget that can be scrolled either using the scrollbars or by dragging...

Tkinter class hierarchy

Unlike many windowing systems, the Tkinter hierarchy is really quite simple in fact, there really isn't a hierarchy at all. The WM, Misc, Pack, Place and Grid classes are mixins to each of the widget classes. Most programmers only need to know about the lowest level in the tree to perform everyday operations and it is often possible to ignore the higher levels. The notional hierarchy is shown in figure 2.4. Figure 2.4 Tkinter widget hierarchy Figure 2.5 Tkinter widgets a collage Figure 2.5...

Data verification

Python Tkinter

An important part of a GUI, which performs data entry, is verifying appropriate input values. This area can consume a considerable amount of time and effort for the programmer. There are several approaches to validating input, but we will not attempt to cover all of them here. Pmw EntryField widgets provide built-in validation routines for common entryfield types such as dates, times and numeric fields. Using these facilities can save you a considerable amount of time. Here is a simple example...

Tkinter variables

Python Tkinter Combobox

The previous example used Pmw widgets to provide setentry and get methods to give access to the widget's content. Tk provides the ability to link the current value of many widgets such as text, toggle and other widgets to an application variable. Tkinter does not support this mode, instead it provides a Variable class which may be subclassed to give access to the variable, textvariable, value, and other options within the widget. Currently, Tkinter supports StringVar, IntVar, DoubleVar and...

Examining the application structure

The calculator example derives its compact code from the fact that Tkinter provides much of the structure for the application. Importing Tkinter establishes the base objects for the system and it only requires a little extra code to display a GUI. In fact, the minimal Tkinter code that can be written is just four lines aWidget Labe1 None, text 'How 1itt1e code does it need ' In this fragment, the label widget is realized with the pack method. A main1oop is necessary to start the Tkinter event...

Tkinter performance

The performance of a GUI can make or break an application. Users have subconscious expectations about how fast something should happen. Even simple interfaces, such as you might see on an Automated Teller Machine ATM , have response times set for various operations usually feedback for every keypress, such as a beep or acknowledgment is less than two seconds and transactions are completed within ten seconds . Consistency is also important. If a GUI normally does something in one second, a user...

Binding widgets to dynamic data

Tkinter provides a simple mechanism to bind a variable to a widget. However, it not possible to use an arbitrary variable. The variable must be subclassed from the Variable class several are predefined and you could define your own, if necessary. Whenever the variable changes, the widget's contents are updated with the new value. Look at this simple example def _init_ self, master None, label '', value 0 self.i Checkbutton master, text label, variable self.var, command self.valueChanged...

The elements of good interface design

Phone Book Notebook Tkinter

User interfaces are really rather simple display a screen, have the user input data and click on a button or two and show the user the result of their actions. This appears to be easy, but unless you pay attention to detail, the end user's satisfaction with the application can be easily destroyed by a badly designed GUI. Of course, appreciation of GUI's is highly subjective and it is almost impossible to satisfy everyone. We are going to develop a number of example interfaces in this chapter...

Canvas

Tkinter Canvas Change Image With Update

Not only can you use them to draw complex objects, using lines, ovals, polygons and rectangles, but you can also place images and bitmaps on the canvas with great precision. In addition to these features you can place any widgets within a canvas such as buttons, listboxes and other widgets and bind mouse or keyboard actions to them. You will see many examples in this book where Canvas widgets have been used to provide a free-form container for a variety of...

Format strings

Format strings provide a mechanism to specify the conversion of Python types passed as arguments to the extension routines. The items in the string must match, in number and type, the addresses supplied in the PyArg_ParseTuple call. Although the type of the arguments is checked with the format string, the supplied addresses are not checked. Consequently, errors here can have a disastrous effect on your application. Since Python supports long integers of arbitrary length, it is possible that the...

Building a Mega Widget

Python Toggle Switch Figure

Now that we have mastered creating objects and subclassing to create new behavior and appearance, we can start to create some even more complex widgets, which will result ultimately in more efficient GUIs, since the code required to generate them will be quite compact. First, we need to collect all of the class definitions for LED, HexNut, Nut and ToggleSwitch in a single class library called Components.py. Next, we are going to create a new class, SwitchIndicator, which displays a toggle...

And now for a more complete example

Python Tkinter Meter

The previous examples have illustrated the overall methods for developing GUI representation of panels and other devices. To further develop this theme we will look at a simple but quite useful example. Many digital multimeters have serial interfaces which allow connection to a computer. I own a RadioShack 22-168A multimeter, which is shown in figure 9.10. The meter has 24 ranges that provide AC DC voltage and current measurements, resistance, capacitance, frequency counting and other...

Gif Bmp and overlays

Non Rectangular Frame Tkinter

The panels and machines introduced in the previous section used drawn interfaces. With a little effort, it is possible to produce a panel or machine that closely resembles the actual device. In some cases, it is necessary to have a little artistic flair to produce a satisfactory result, so an alternate approach must be used. Sometimes, it can be easier to use photographs of the device to produce a totally accurate representation of it this is particularly true if the device is large. In this...

The Entry widget

Table A.25 Entry widget standard options -background color -borderwidth width -cursor cursor -exportselection boolean -font font -foreground color -highlightbackground color -highlightcolor color -highlightthickness width -insertbackground color -insertborderwidth width -insertofftime milliseconds -insertontime -relief flat groove raised ridge sunken -selectbackground color -selectborderwidth width -selectforeground color -state NORMAL DISABLED ACTIVE -takefocus focusType -textvariable variable...

The Canvas widget

Table A.3 Canvas widget standard options -background color -borderwidth width -cursor cursor -height height -highlightbackground color -highlightcolor color -highlightthickness number -insertbackground color -insertborderwidth width -insertofftime milliseconds -insertontime milliseconds -insertwidth width -relief flat groove raised ridge sunken -selectbackground color -selectborderwidth width -selectforeground color -takefocus focusType -width width -xscrollcommand tclCommand -yscrollcommand...

Notebooks

Tkinter Notebook

Notebooks sometimes referred to as style or property sheets have become a common motif for user interfaces. One large advantage is that they allow the form designer to display a large number of entry fields without overwhelming the user. Additionally, the fields can be arranged in related groupings, or less-important fields can be separated from fields which are frequently changed. The next example demonstrates the use of notebooks, data dictionaries and AppShell to present the same basic data...

Stretching canvas objects

A common operation for drawing programs is stretching an existing object. This requires us to provide grab handles which the user can click and drag to resize the object. Before we add resize operations to our drawing example, let's take a look at a slightly simpler example which was also converted from Tk. This little program allows you to experiment with the two attributes that determine the shape of an arrow, width and arrowshape. You might find this a useful tool if you ever want to create...

Description of the megawidget

Arc Pygame

This widget will implement a simple gauge which tracks an integer value supplied by a Scale widget, which selects a number from a range. The gauge indicates the setting as a percentage of the range. The completed megawidget will look like the one shown in figure 4.52. The scale widget will be a component of the megawidget since the range may be set by the programmer the size and color of the gauge may similarly be changed, as appropriate for the application, so we make this a component, too. In...

Speed drawing

In general, creating canvas objects is relatively efficient and rarely causes a performance problem. However, for very complex drawings, you may notice a delay in drawing the canvas. This is particularly noticeable when the display contains a large number of objects or when they contain complex line segments. One way of improving drawing performance is to draw the canvas as an image. The Python Imaging Library, which was introduced briefly in chapter 5 on page 89, has the facility to draw...

Rulerclass tools

Python Application

Another common drawing tool is a ruler. This can be used to provide tab stops or other constraint graphics. It also illustrates some of the aspects of drag-and-drop from within an application. This example was also recoded from a Tk example. def _init_ self, master, width '14.8c', height '2.5c' Label master, text This canvas widget shows a mock-up of a ruler. You can create tab stops by dragging them out of the well to the right of the ruler. You can also drag existing tab stops. If you drag a...