Quick Geometry Lesson

Before I show you PyClock, though, a little background and a confession. Quick -how do you plot points on a circle This, along with time formats and events, turns out to be a core concept in clock widget programs. To draw an analog clock face on a canvas widget, you essentially need to be able to sketch a circle -- the clock face itself is composed of points on a circle, and the second, minute, and hour hands of the clock are really just lines from a circle's center out to a point on the...

Quick Introduction to JPython

Functionally speaking, JPython is a collection of Java classes that run Python code. It consists of a Python compiler, written in Java, that translates Python scripts to Java bytecodes so they can be executed by a Java virtual machine -- the runtime component that executes Java programs and is used by major web browsers. Moreover, JPython automatically exposes all Java class libraries for use in Python scripts. In a nutshell, here's what comes with the JPython system JPython always compiles...

A rand module replaced by random module

The rand module is now deprecated use random instead. A.3.2.9 Assorted Tkinter changes Tkinter became portable to and sprouted native look-and-feel for all major platforms (Windows, X, Macs). There has been a variety of changes in the Tkinter GUI interface The_call__method for StringVar class objects was dropped in Python 1.4 that means you need to explicitly call their get ( ) set( ) methods, instead of calling them with or without arguments. The ScrolledText widget went through a minor...

Simple JPython Example

Once a Python program is compiled with JPython, it is all Java the program is translated to Java bytecodes, it uses Java classes to do its work, and there is no Python left except for the original source code. Because the compiler tool itself is also written in Java, JPython is sometimes called 100 pure Java. That label may be more profound to marketeers than programmers, though, because JPython scripts are still written using standard Python syntax. For instance, Example 15-4 is a legal...

Add Python Mix Well Repeat

In the last chapter, we explored half of the Python C integration picture -- calling C services from Python. This mode lets programmers speed up operations by moving them to C, and utilize external libraries by wrapping them in C extension modules and types. But the inverse can be just as useful -- calling Python from C. By delegating selected components of an application to embedded Python code, we can open them up to onsite changes without having to ship a system's code. This chapter tells...

Adding Relational Algebra to Sets CD

If you are interested in studying additional set-like operations coded in Python, see the following files on this book's CD (see PP2E Dstruct Basic rset.py RSet implementation PP2E Dstruct Basic reltest.py Test script for RSet The RSet subclass defined in rset.py adds basic relational algebra operations for sets of dictionaries. It assumes the items in sets are mappings (rows), with one entry per column (field). RSet inherits all the original Set operations (iteration, intersection, union, &...

Administrative Tools

Now that we have finished implementing a Python-powered, web-enabled, concurrently accessible report database, and published web pages and scripts that make that database accessible to the cyberworld at large, we can sit back and wait for reports to come in. Or almost there still is no way for the site owner to view or delete records offline. Moreover, all records are tagged as not yet verified on submission, and must somehow be verified or rejected. This section lists a handful of tersely...

Alternative encryption schemes

To show how to write alternative encryptors and encoders, secret also includes a digits-string encoder and a character-code shuffling encryptor both are enabled with global flag variables at the top of the module If set to true, the encrypted password is encoded into a string of ASCII code digits separated by dashes. Defaults to false to fall back on URL and HTML escape encoding. If set to false and the encryptor is used on an even-numbered day of the week, the simple character-code encryptor...

Anatomy of a C Extension Type

Although most of file stacktyp.c is missing, there is enough here to illustrate the global structure common to C type implementations The file starts off by defining a C struct called stackobject that will be used to hold per-instance state information -- each generated instance object gets a newly malloc'd copy of the struct. It serves the same function as class instance attribute dictionaries, and contains data that was saved in global variables by the C stack module. As in the module, a set...

And Now for Something Completely Different

This book is about using Python, a very high-level, object-oriented, open source111 programming language, designed to optimize development speed. Although it is completely general-purpose, Python is often called an object-oriented scripting language, partly because of its sheer ease of use, and partly because it is commonly used to orchestrate or glue other software components in an application. 11 Open source systems are sometimes called freeware, in that their source code is freely...

And Now for Something Completely Different Again

The first edition of this book was one of the first to present the Python language. This second edition is an almost completely new advanced Python topics book, designed to be a follow-up to the core language material in Learning Python and supplemented by the reference material in Python Pocket Reference. That is, this edition is focused on ways to use Python, rather than on the language itself. Python development concepts are explored along the way -- in fact, they really become meaningful...

Appendix A Recent Python Changes

This appendix summarizes prominent changes introduced in Python releases since the first edition of this book. It is divided into three sections, mostly because the sections on 1.6 and 2.0 changes were adapted from release note documents Changes introduced in Python 2.0 (and 2.1) Changes between the first edition and Python 1.5.2 Python 1.3 was the most recent release when the first edition was published (October 1996), and Python 1.6 and 2.0 were released just before this second edition was...

Appendix B Pragmatics

This appendix is a very brief introduction to some install-level details of Python use, and contains a list of Python Internet resources. More information on topics not covered fully here can be found at other resources For additional install details, consult the various README text files in the examples distribution on this book's CD (view CD-ROM content online at http examples.oreilly.com python2), as well as the README files and other documentation that accompany the Python distributions and...

Application Hierarchy Superclasses

This section lists the source code of StreamApp and App -- the classes that do all this extra work on behalf of PackApp and UnpackApp. We don't have space to go through all this code in detail, so be sure to study these listings on your own for more information. It's all straight Python code. I should also point out that the classes listed in this section are just the ones used by the object-oriented mutations of the textpack and textunpack scripts. They represent just one branch of an overall...

Attaching widgets to frames

In larger terms, the critical innovation in this example is its use of frames Frame widgets are just containers for other widgets, and so give rise to the notion of GUIs as widget hierarchies, or trees. Here, win serves as an enclosing window for the other three widgets. In general, though, by attaching widgets to frames, and frames to other frames, we can build up arbitrary GUI layouts. Simply divide the user interface into a set of increasingly smaller rectangles, implement each as a Tkinter...

Python Internet Resources

Finally, Table B-1 lists some of the most useful Internet sites for Python information and resources. Nearly all of these are accessible from Python's home page (http www.python.org) and most are prone to change over time, so be sure to consult Python's home page for up-to-date details. comp.lang.python (python-list cwi.nl) http www.rmi. net lutz about-pp2e.html

Running Python Programs

Python code can be typed at a > > > interactive prompt, run from a C program, or placed in text files and run. There is a variety of ways to run code in files Python files can always be run by typing a command of the form python file.py in your system shell or console box, as long as the Python interpreter program is on your system's search path. On Windows, you can type this command in an MS-DOS console box on Linux, use an xterm. Depending on your platform, you can usually start Python...

Running the Demo Launcher Scripts

The top level of the CD's Examples PP2E package (see http examples.oreilly.com python2) includes Python self-configuring scripts that can be run to launch major book examples, even if you do not configure your environment. That is, they should work even of you don't set your PATH or PYTHONPATH shell variables. These two scripts, PyDemos and PyGadgets, are presented in Chapter 8, and described more fully in both this book's Preface and the CD's README files (see http examples.oreilly.com...

The Book Examples Package

The Examples PP2E CD directory is a Python module package that contains source code files for all examples presented in this book (and more). The PP2E package in turn contains nested module packages that partition the example files into subdirectories by topic. You can either run files straight off the CD, or copy the PP2E directory onto your machine's hard drive (copying over allows you to change the files, and lets Python store their compiled bytecode for faster startups). Either way, the...

Binding Events

We met the bind widget method in the last chapter, when we used it to catch button presses in the tutorial. Because bind is commonly used in conjunction with other widgets (e.g., to catch return key presses for input boxes), we're going to make a stop early on the tour here as well. Example 7-15 illustrates more bind event protocols. print 'Widget s X s Y s' (event.widget, event.x, event.y) def showAllEvent(event) print event print attr, ' > ', getattr(event, attr) print 'Got left mouse...

Binding events on specific items

Much like we did for the Text widget, it is also possible to bind events for one or more specific objects drawn on a Canvas with its tag_bind method. This call accepts either a tag name string or object ID in its first argument. For instance, you can register a different callback handler for mouseclicks on every drawn item, or on any in a group of drawn and tagged items, rather than for the entire canvas at large. Example 8-16 binds a double-click handler in both the canvas itself and on two...

But Its Still Not a Reference Manual

Please note that this edition, like the first, is still more of a tutorial than a reference manual (despite sharing a title pattern with a popular Perl reference text). This book aims to teach, not document. You can use its table of contents and index to track down specifics, and the new structure helps make this easy to do. But this edition is still designed to be used in conjunction with, rather than to replace, Python reference manuals. Because Python's manuals are free, well-written,...

CGI Script Tradeoffs

As shown in this chapter, PyMailCgi is still something of a system in the making, but it does work as advertised by pointing a browser at the main page's URL, I can check and send email from anywhere I happen to be, as long as I can find a machine with a web browser. In fact, any machine and browser will do Python doesn't even have to be installed.151 That's not the case with the PyMailGui client-side program we wrote in Chapter 11. 5 This property can be especially useful when visiting...

Checking for Missing and Invalid Inputs

So far, we've been triggering the CGI script by selecting a language name from the pull-down list in the main HTML page. In this context, we can be fairly sure that the script will receive valid inputs. Notice, though, that there is nothing to prevent a user from passing the requested language name at the end of the CGI script's URL as an explicit parameter, instead of using the HTML page form. For instance, a URL of the form yields the same Python response page shown in Fj ure_12-.2Q.iim...

Client socket calls

On the other hand, client programs like the one shown in Example 10-2 follow simpler call sequences. The main thing to keep in mind is that the client and server must specify the same port number when opening their sockets, and the client must identify the machine on which the server is running (in our scripts, server and client agree to use port number 50007 for their conversation, outside the standard protocol range) sockobj socket(AF_INET, SOCK_STREAM) Creates a Python socket object in the...

Coding for reusability

A postscript I coded all the demo launcher bars deployed by the last three examples to demonstrate all the different ways that their widgets can be used. They were not developed with general-purpose reusability in mind in fact, they're not really useful outside the context of introducing widgets in this book. That was by design most Tkinter widgets are easy to use once you learn their interfaces, and Tkinter already provides lots of configuration flexibility by itself. But if I had in mind to...

Commercially Published References

At the risk of sounding like a marketing droid, I should mention that you can also purchase the Python manual set, printed and bound see the book information page at http www.python.org for details and links. Commercially published Python reference books are also available today, including Python Essential Reference (New Riders Publishing) and Python Pocket Reference (O'Reilly). The former is more complete and comes with examples, but the latter serves as a convenient memory-jogger once you've...

Common conversion codes

With a few exceptions, PyArg_Parse(Tupie) and Py_BuiidVaiue use the same conversion codes in format strings. A list of all supported conversion codes appears in Python's extension manuals. The most commonly used are shown in Table 19-1 the tuple, list, and dictionary formats can be nested. These codes are mostly what you'd expect (e.g., i maps between a C int and a Python integer object), but here are a few usage notes on this table's entries Pass in the address of a char* for s codes when...

Common input devices alternative layout

Ult wm taw flcnpt, '-.-j. ill.lut afju'. ot Lit mci iLtli Nulid Lilt sipormiM f li f-1 int rferf an jr-ic-tame lege h(ne. th r Cj iCf -T ' M'.iii-in ltiif - f tic n- d o i .** rzjct wit* lie u.-er cLejit iiniphiflf lilt- r.illtm inn Ciiltti mini I ii< k .SlilirniE iiniphiflf lilt- r.illtm inn Ciiltti mini I ii< k .SlilirniE ------Kfti-i-in -H's 'y-Ai . * Now, before you go blind trying to detect the differences in this and the prior HTML file, I should note that the HTML differences that...

Compiling and Running

This C extension file is compiled and dynamically or statically linked like previous examples file makefile.stack on the CD (see http examples.oreilly.com python2) handles the build like this gcc stacktyp.c -g -I (PY) Include -I (PY) -fpic -shared -o stacktype.so Once compiled, you can import the C module and make and use instances of the C type it defines much as if it were a Python class (but without inheritance). You would normally do this from a Python script, but the interactive prompt is...

CPPEpython Launch Browserpy live lutz starshippythonnet

Opening http starship.python.net lutz Starting In Chapter 8, we'll see that this script is also run to start Internet examples in the top-level demo launcher system the PyDemos script presented in that chapter portably opens local or remote web page files with this button-press callback pagepath os.getcwd( ) + ' Internet Cgi-Web' demoButton('PyErrata', 'Internet-based errata report system', 'LaunchBrowser.py -file s PyErrata pyerrata.html' pagepath) site 'starship.python.net lutz'...

Ctempfc B pyexe mypyexe

Comparing files py152.exe and mypy152.exe FC no differences encountered Finally, the splitter is also smart enough to create the output directory if it doesn't yet exist, or clear out any old files there if it does exist. Because the joiner combines whatever files exist in the output directory, this is a nice ergonomic touch -- if the output directory was not cleared before each split, it would be too easy to forget that a prior run's files are still there. Given that my kids are running these...

CWD and Command Lines

This distinction between the CWD and import search paths explains why many scripts in this book designed to operate in the current working directory (instead of one whose name is passed in) are run with command lines like this C temp> python X PyTools cleanpyc-py.py In this example, the Python script file itself lives in the directory C PP2ndEd examples PP2E PyTools, but because it is run from C temp, it processes the files located in C temp (i.e., in the CWD, not in the script's home...

CWD Files and Import Paths

When you run a Python script by typing a shell command line like python dir1 dir2 file.py, the CWD is the directory you were in when you typed this command, not dir1 dir2. On the other hand, Python automatically adds the identity of the script's home directory to the front of the module search path, such that file.py can always import other files in dir1 dir2, no matter where it is run from. To illustrate, let's write a simple script to echo both its CWD and module search path whereami.py...

Data Structures Versus Python Builtins

Now that I've shown you all these complicated algorithms, I need to also tell you that at least in some cases, they may not be an optimal approach. Built-in types like lists and dictionaries are often a simpler and more efficient way to represent data. For instance These may be useful in many applications, but Python dictionaries already provide a highly optimized, C-coded, search table tool. Indexing a dictionary by key is likely to be faster than searching a Python-coded tree structure >...

Debugging CGI scripts

Errors happen, even in the brave new world of the Internet. Generally speaking, debugging CGI scripts can be much more difficult than debugging programs that run on your local machine. Not only do errors occur on a remote machine, but scripts generally won't run without the context implied by the CGI model. The script in Example 12-11 demonstrates the following two common debugging tricks. This script assigns sys.stderr to sys.stdout so that Python error messages wind up being displayed in the...

Decoding base data

Mail messages and attachments are frequently sent in an encoding format such as uu or base64 binary data files in particular must be encoded in a textual format for transit using one of these encoding schemes. On the receiving end, such encoded data must first be decoded before it can be viewed, opened, or otherwise used. The Python program in Example 11-19 knows how to perform base64 decoding on data stored in a file. Example 11-19. PP2E Internet Email...

Designing for Reuse and Growth

I admit it PyErrata may be thrifty, but it's also a bit self-centered. The database interfaces presented in the prior sections work as planned and serve to separate all database processing from CGI scripting details. But as shown in this book, these interfaces aren't as generally reusable as they could be moreover, they are not yet designed to scale up to larger database applications. Let's wrap up this chapter by donning our software code review hats for just a few moments and exploring some...

Downloading Web Sites Mirrors

Once upon a time, Telnet was all I needed. My web site lived at an Internet Service Provider (ISP) that provided general and free Telnet access for all its customers. It was a simple time. All of my site's files lived only in one place -- at my account directory on my ISP's server machine. To make changes to web pages, I simply started a Telnet session connected to my ISP's machine and edited my web pages there online. Moreover, because Telnet sessions can be run from almost any machine with an...

Endofline translations on Windows

Strictly speaking, on some platforms you may not need the b at the end of the open mode argument to process binary files the b is simply ignored, so modes r and w work just as well. In fact, the b in mode flag strings is usually only required for binary files on Windows. To understand why, though, you need to know how lines are terminated in text files. For historical reasons, the end of a line of text in a file is represented by different characters on different platforms it's a single n...

Escaping mail text and passwords in HTML

Notice that everything you see on the message view page in Figure 13-13 is escaped with cgi.escape. Header fields and the text of the mail itself might contain characters that are special to HTML and must be translated as usual. For instance, because some mailers allow you to send messages in HTML format, it's possible that an email's text could contain a < textarea> tag, which would throw the reply page hopelessly out of sync if not escaped. One subtlety here HTML escapes are important...

Escaping URLs Embedded in HTML Code

But what do we do for URLs inside HTML That is, how do we escape when we generate and embed text inside a URL, which is itself embedded inside generated HTML code Some of our earlier examples used hardcoded URLs with appended input parameters inside < a href> hyperlink tags file languages2.cgi, for instance, prints HTML that includes a URL < a Because the URL here is embedded in HTML, it must minimally be escaped according to HTML conventions (e.g., any < characters must become & lt...

Evaluating expressions with stacks

Now that you have the general idea of what PyCalc does, I need to say a little bit about how it does what it does. Most of the changes in this version involve managing the expression display and evaluating expressions. PyCalc is structured as two classes The caicGui class manages the GUI itself. It controls input events and is in charge of the main window's display field at the top. It doesn't evaluate expressions, though for that, it sends operators and operands entered in the GUI to an...

Example PPEDbaseguitoolspy

added extras for entry width, calcgui font color def frame(root, side, **extras) widget Frame(root) widget.pack(side side, expand YES, fill BOTH) if extras apply(widget.config, ( ), extras) return widget def label(root, side, text, **extras) widget Label(root, text text, relief RIDGE) widget.pack(side side, expand YES, fill BOTH) if extras apply(widget.config, ( ), extras) return widget def button(root, side, text, command, **extras) widget Button(root, text text, command command)...

Example PPEDbasetestdatapy

definitions for testing shelves, dbm, and formgui cast definitions for testing shelves, dbm, and formgui cast def init (self, name ( ), job '') no need for arg def init (self, name ( ), job '') no need for arg self.job job def setattr (self, attr, value) print 'validation error kids ', if attr 'name' and type(value) t print 'validation error name type self.__dict__ attr value The cast object here is intended to represent a table of records (it's really a dictionary of dictionaries when written...

Example PPEDstruct Basicstackpy

For x in start self.push(x) self.reverse( ) self.stack obj + self.stack def pop(self) if not self.stack raise error, 'underflow' top, self.stack self.stack 0 , self.stack 1 return top def top(self) if not self.stack raise error, 'underflow' return self.stack 0 def empty(self) return ' Stack s ' self.stack backquotes, return Stack(self.stack + other.stack) instance2 return Stack(self.stack * reps) def getitem (self, offset) return self.stack offset return Stack(self.stack low high ) def getattr...

Example PPEDstruct Classicsgtestobjpy

S.arcs P, M P.arcs S, M, A A.arcs M print S.search(M) This test finds three paths in its graph between nodes S and M. If you'd like to see more Python graph code, check out the files in directory MoreGraphs on the CD (see http examples.oreilly.com python2). These are roughly the same as the ones listed here, but add user interaction as each solution is found. In addition, we've really only scratched the surface of this domain here see other books for additional topics (e.g., breadth- and...

Example PPEDstruct Classicspermcombpy

If size 0 or not list matters here for i in range(len(list)) pick list i i+1 for x in subset(rest, size-1) result.append(pick + x) return result if size 0 or not list doesn't matter for i in range(0, (len(list) - size) pick list i i+1 rest list i+1 for x in combo(rest, size - 1) result.append(pick + x) return result As in the reversal functions, all three of these work on any sequence object that supports len, slicing, and concatenation operations. For instance, we can use permute on instances...

Example PPEDstruct TreeViewtreeviewpy

wrappers for viewing tree types in the book, plus test cases gui from treeview wrappers import TreeWrapper, TreeViewer from PP2E.Dstruct.Classics import btree from PP2E.Lang.Parser import parser2 binary tree wrapper class BinaryTreeWrapper(TreeWrapper) embed binary tree in def children(self, node) adds viewer protocols return None def label(self, node) try return str(node) def onInputLine(self, line, viewer) t btree.BinaryTree( ) for x in items t.insert(x) binary tree extension class...

Example PPEGui Clockclockpy

PyClock a clock GUI, with both analog and digital display modes, a popup date label, clock face images, resizing, etc. May be run both stand-alone, or embbeded (attached) in other GUIs that need a clock. from Tkinter import * import math, time, string Option configuration classes defaults--override in instance or subclass size 200 hh, mh, sh, cog 'black', 'navy', 'blue', 'red' center class PhotoClockConfig(ClockConfig) sample configuration size 320 bg, hh, mh 'white', 'blue', 'orange' Digital...

Example PPEGui ShellGuipackdlgpy

added file select dialogs, empties test could use grids from glob import glob filename from Tkinter import * gui widget from tkFileDialog import * file selector from PP2E.System.App.Clients.packapp import PackApp use pack s1, s2 StringVar(), StringVar( ) function output, patterns s1.get(), s2.get( ) destroy if output and patterns patterns string.split(patterns) filenames for sublist in map(glob, patterns) filenames filenames + sublist run class like a pop-up dialog sets app PackApp(ofile...

Example PPEGui TextEditorsimpleshellpy

Line raw input('> > > ') single line statements only exec line in namespace or eval( ) and print result Depending on the user's preference, PyEdit either does something similar to this to run code fetched from the text widget, or uses the launchmodes module we wrote at the end of Chapter 3 to run the code's file as an independent program. There are a variety of options in both schemes that you can customize as you like (this is Python, after all). See the onRunCode method for details, or...

Example PPEGui TextEditortext Editorpy

PyEdit 1.1 a Python Tkinter text file editor and component. Uses the Tk text widget, plus GuiMaker menus and toolbar buttons to implement a full-featured text editor that can be run as a stand-alone program, and attached as a component to other GUIs. Also used by PyMail and PyView to edit mail and image file notes. from PP2E.Gui.Tools.guimaker import * SEL_FIRST SEL + '.first' SEL_LAST SEL + '.last' import sys, os, string FontScale 0 9+FontScale, l2+FontScale, lO+FontScale, lO+FontScale,...

Example PPEGui Toolsguimakerpy

An extended Frame that makes window menus and tool-bars automatically. Use GuiMakerFrameMenu for embedded components (makes frame-based menus). Use GuiMakerWindowMenu for top-level windows (makes Tk8.0 window menus). See the self-test code (and PyEdit) for an example layout tree format. from Tkinter import * from types import * class GuiMaker(Frame) menuBar toolBar subclasses def init (self, parent None) Frame. init (self, parent) self.pack(expand YES, fill BOTH) stretchable make menu bar at...

Example PPEGui Toolsguimixinpy

a mixin class for other frames common methods for canned-dialogs, spawning programs, etc must be mixed with a class derived from Frame for its quit method from ScrolledText import ScrolledText from PP2E.launchmodes import PortableLauncher, System def infobox(self, title, text, *args) dialogs return showinfo(title, text) bkwd compat def question(self, title, text, *args) return askyesno(title, text) showerror('Not implemented', 'Option not available') def quit(self) ans self.question('Verify...

Example PPEGui ToolsReloadradpy

Import actions get initial callback handlers def init (self, master None) Frame. init (self, master) self.pack( ) self.make widgets( ) Button(self, text 'message1', Button(self, text 'message2', reload(actions) need to reload actions module before actions.message1( ) now new version triggered by print 'exposed method ' called from actions function When run, this script makes a two-button window that triggers the message1 and message2 methods. Example 9-12 contains the actual callback handlers'...

Example PPEGui Touralarmhidepy

Class Alarm(alarm.Alarm) change alarm def init (self, msecs 1000) self.shown 0 self.after(self.msecs, self.repeater) def init (self, msecs 1000) self.shown 0 self.after(self.msecs, self.repeater) When this script is run, the same window appears, but the button is erased or redrawn on alternating timer events. The widget pack_forget method erases (unmaps) a drawn widget, and pack makes it show up again grid_forget and grid similarly hide and show widgets in a grid. The pack_forget method is...

Example PPEGui Tourbuttonpicsfuncpy

From Tkinter import * from glob import glob import demoCheck import random gifdir ' gifs ' attach checkbutton demo to me lbl Label(root, text none, bg 'blue', fg 'red') pix Button(root, text Press me, command draw, bg 'white') demoCheck.Demo(root, relief SUNKEN, bd 2).pack(fill BOTH) files glob(gifdir + *.gif) now images map(lambda x (x, PhotoImage(file x)), files) hold This code uses a handful of built-in tools from the Python library The Python glob module we met earlier in the book gives a...

Example PPEGui Tourcanvasbindpy

Print 'Got canvas click', event.x, event.y, event.widget def onObjectClick(event) print 'Got object click', event.x, event.y, event.widget, print event.widget.find closest(event.x, event.y) find text object's id canv Canvas(root, width 100, height 100) obj1 canv.create text(50, 30, text 'Click me one') obj2 canv.create text(50, 70, text 'Click me two') canv.bind('< Double-1> ', onCanvasClick) canvas canv.tag bind(obj1, '< Double-1> ', onObjectClick) item canv.tag bind(obj2, '<...

Example PPEGui TourcanvasDrawpy

draw elastic shapes on a canvas on drag, move on right click see canvasDraw tags*.py for extensions with tags and animation canvas Canvas(width 300, height 300, bg 'beige') canvas.pack() canvas.bind('< ButtonPress-1> ', self.onStart) click and drag event x,y when scrolled to bottom of canvas canvas x,y -y differs radically when scrolled to a mid point in the canvas delete all canvas.bind('< ButtonPress-3> ', self.onMove) move latest self.canvas canvas self.drawn None self.kinds...

Example PPEGui Tourconfigbuttonpy

Widget Button(text 'Spam', padx 10, pady 10) widget.pack(padx 2 0, pady 20) widget.config(cursor 'gumby') widget.config(bd 8, relief RAISED) widget.config(bg 'dark green', fg 'white') widget.config(font (,helvetica', 20, 'underline italic')) mainloop() To see the effects generated by these two script's settings, try out a few changes on your computer. Most widgets can be given a custom appearance in the same way, and we'll see such options used repeatedly in this text. We'll also meet...

Example PPEGui Tourconfiglabelpy

Labelfont ('times', 20, 'bold') style widget Label(root, text 'Hello config world') widget.config(bg 'black', fg 'yellow') black label widget.config(height 3, width 20) initial size widget.pack(expand YES, fill BOTH) root.mainloop() Remember, we can call a widget's config method to reset its options at any time, instead of passing them all to the object's constructor. Here, we use it to set options that produce the window in Figure 7-1. Figure 7-1. A custom label appearance Figure 7-1. A custom...

Example PPEGui TourdemoAllfrmpy

4 demo class components (subframes) on one window there are 5 Quitter buttons on this one window too guis can be reused as frames, windows, processes from Tkinter import * from quitter import Quitter demoModules 'demoDlg', 'demoCheck', 'demoRadio', 'demoScale' parts part.config(bd 2, relief GROOVE) part.pack(side LEFT, fill BOTH) parts.append(part) for part in parts run demo report print part. module + ' ', if hasattr(part, 'report') Label(root, text 'Multiple Frame demo', bg 'white').pack()...

Example PPEGui TourdemoCheckpy

From Tkinter import * get base widget set from dialogTable import demos get canned dialogs from quitter import Quitter attach a quitter object to me def init (self, parent None, **args) Frame. init (self, parent, args) self.pack() self.tools() Label(self, text Check demos).pack() self.vars for key in demos.keys() var IntVar() Checkbutton(self, command demos key ).pack(side LEFT) self.vars.append(var) print var.get(), current toggle settings 1 or 0 print def tools(self) frm Frame(self)...

Example PPEGui TourdemoDlgpy

From Tkinter import * get base widget set from dialogTable import demos button callback handlers from quitter import Quitter attach a quit object to me def init (self, parent None) Frame.__init__(self, parent) self.pack() Label(self, text Basic demos).pack() for (key, value) in demos.items() Button(self, text key, command value).pack(side TOP, Quitter(self).pack(side TOP, fill BOTH) if name ' main ' Demo().mainloop() This script creates the window shown in Figure 7-11 when run as a standalone...

Example PPEGui Tourdlgcustompy

From Tkinter import * makemodal (len(sys.argv) > 1) Label(win, text 'Hard drive reformatted ').pack() add a few widgets Button(win, text 'OK', command win.destroy).pack() set destroy callback win.focus set() take over input focus, win.grab set() disable other windows while I'm win.wait window() and wait here until win destroyed print 'dialog exit' else returns right away Button(root, text 'popup', command dialog).pack() root.mainloop() This script is set up to create a pop-up dialog window in...

Example PPEGui Tourdlgoldpy

From Tkinter import * from Dialog import Dialog def init (self, master None) Frame. init (self, master) Pack.config(self) same as self.pack() Button(self, text 'Pop1', command self.dialog1).pack() Button(self, text 'Pop2', command self.dialog2).pack() def dialog1(self) text 'An example of a popup-dialog ' 'box, using older Dialog.py.', bitmap 'questhead', default 0, strings ('Yes', 'No', 'Cancel')) if ans.num 0 self.dialog2() def dialog2(self) text I'm afraid I can't let you do that, default 0,...

Example PPEGui Tourentrymodalpy

must fetch before destroy with entries from Tkinter import * from entry2 import makeform, fetch, fields fetch(entries) must fetch before window popup.destroy() fails with msgs if stmt order is popup Toplevel() show form in modal dialog window Button(popup, text 'OK', command (lambda e ents show(e)) ).pack() popup.grab set() popup.focus set() popup.wait window() wait for destroy here Button(root, text 'Dialog', command ask).pack() root.mainloop() When run, pressing the button in this program's...

Example PPEGui TourGridgridpy

Label(root, text 'Grid').grid(columnspan 2) r 1 l Label(root, text c, relief RIDGE, width 25) e Entry(root, bg c, relief SUNKEN, width 50) l.grid(row r, column 0, sticky NSEW) e.grid(row r, column 1, sticky NSEW) root.rowconfigure(r, weight 1) root.columnconfigure(0, weight 1) root.columnconfigure(1, weight 1) Label(root, text 'Pack').pack() for c in colors l Label(f, text c, relief RIDGE, width 25) e Entry(f, bg c, relief SUNKEN, width 50) f.pack(side TOP, expand YES, fill BOTH) l.pack(side...

Example PPEGui TourimgCanvaspy

Gifdir gifs from sys import argv from Tkinter import * filename (len(argv) > 1 and argv 1 ) or 'ora-lp.gif' name on img PhotoImage(file gifdir+filename) can Canvas(win) can.pack(fill BOTH) can.config(width img.width(), height img.height()) size to img can.create image(2, 2, image img, anchor NW) win.mainloop() Figure 7-38. Sizing the canvas to match the photo Figure 7-38. Sizing the canvas to match the photo And that's all there is to it. In Chapter 8, well see images show up in a Menu, other...

Example PPEGui Tourmbuttonpy

Menu(mbutton) config(menu picks) picks.add command(label 'spam', picks.add command(label 'eggs', picks.add command(label 'bacon', mbutton.pack() mbutton.config(bg 'white,, bd 4, root.mainloop() command root.quit) command root.quit) command root.quit) Figure 8-8. A Menubutton all by itself Figure 8-8. A Menubutton all by itself The related Tkinter Optionmenu widget displays an item selected from a pull-down menu. It's roughly like a Menubutton plus a display label, and displays a menu of...

Example PPEGui Tourmenuwinmultipy

From menu win import makemenu from Tkinter import * for i in range(3) 3 popup windows with menus Label(win, bg 'black', height 5, width 15).pack(expand YES, fill BOTH) Button(root, text Bye, command root.quit).pack() root.mainloop() Figure 8-3. A File tear-off and Edit cascade Figure 8-3. A File tear-off and Edit cascade Figure 8-4. Multiple Toplevels with menus Figure 8-4. Multiple Toplevels with menus

Example PPEGui Touroptionmenupy

From Tkinter import * root Tk() varl StringVar() var2 StringVar() optl OptionMenu(root, varl, 'spam', 'eggs', 'toast') like opt2 OptionMenu(root, var2, 'ham', 'bacon', 'sausage') but shows choice opt1.pack(fill X) opt2.pack(fill X) varl.set('spam') var2.set('ham') def state() print var1.get(), var2.get() linked Button(root, command state, text 'state').pack() root.mainloop() There are other menu-related topics that we'll skip here in the interest of space. For instance, scripts can add entries...

Example PPEGui Tourquitterpy

a quit button that verifies exit requests to reuse, attach an instance to other guis from tkMessageBox import askokcancel def init (self, parent None) Frame. init (self, parent) self.pack() widget Button(self, text 'Quit' widget.pack(side LEFT) def quit(self) ans askokcancel('Verify exit', if ans Frame.quit(self) if name ' main ' Quitter().mainloop() This module is mostly meant to be used elsewhere, but puts up the button it implements when run standalone. Figure 7-10 shows the Quit button...

Example PPEGui Tourscrolledcanvaspy

Def init (self, parent None, color 'brown') Frame. init (self, parent) self.pack(expand YES, fill BOTH) expandable canv Canvas(self, bg color, relief SUNKEN) canv.config(width 300, height 200) area size canv.config(scrollregion (0,0,300, 1000)) canv.config(highlightthickness 0) to border sbar Scrollbar(self) sbar.config(command canv.yview) canv.config(yscrollcommand sbar.set) moves other sbar.pack(side RIGHT, fill Y) first clip last canv.pack(side LEFT, expand YES, fill BOTH) clipped first...

Example PPEGui Toursimpleeditpy

add common edit tools to scrolled text by inheritance composition (embedding) would work just as well here this is not robust see PyEdit for a feature superset from tkSimpleDialog import askstring from tkFileDialog import asksaveasfilename from scrolledtext import ScrolledText class SimpleEditor(ScrolledText) for more def init (self, parent None, file None) frm Frame(parent) frm.pack(fill X) Button(frm, text 'Save', command self.onSave).pack(side LEFT) Button(frm, text 'Cut', command...

Example PPEGui Tourtoplevelpy

From Tkinter import Toplevel, Button, Label winl Toplevel() two independent windows win2 Toplevel() but part of same process Button(win1, text 'Spam', command sys.exit).pack() Button(win2, text 'SPAM', command sys.exit).pack() Label(text 'Popups').pack() on default Tk() root window The toplevelo script gets a root window by default (that's what the Label is attached to, since it doesn't specify a real parent), but also creates two standalone Toplevel windows that appear and function...

Example PPEIntegrate EmbedBasicsmakefilebasics

build all 5 basic embedding examples with external module libs linked in source setup-pp-embed.csh if needed -lgdbm -ltk8.0 -ltcl8.0 -lX11 -lm -ldl BASICS embed-simple embed-string embed-object embed-dict embed-bytecode gcc embed *.o (PYLIB) (LIBS) -g -export-dynamic -o embed * This version links in Tkinter libraries because the Python library file it uses was built with Tkinter enabled. You may have to link in arbitrarily many more externals for your Python library, and frankly, chasing down...

Example PPEIntegrate EmbedHigh LevelApippembedh

* AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE * Wraps Python's run-time embedding API functions for easy use. * Most utilities assume the call is qualified by an enclosing module * (namespace). The module can be a file-name reference or a dummy module * created to provide a namespace for file-less strings. These routines * automate debugging, module (re)loading, input output * Python is automatically initialized when the first API call occurs. * Input output conversions use the standard Python...

Example PPEIntegrate EmbedInventoryvalidatepy

embedded validation code, run from C input vars PRODUCT, QUANTITY, BUYER output vars ERRORS, WARNINGS import string all python tools are available import inventory plus C extensions, Python msgs, errs , warning, error message lists if PRODUCT not in inventory.skus( ) this errs.append('bad-product') from a user- elif QUANTITY > inventory.stock(PRODUCT) inventory.reduce(PRODUCT, QUANTITY) if inventory.stock(PRODUCT) QUANTITY < 2 msgs.append('reorder-soon ' + 'PRODUCT') first, last BUYER 0 ,...

Example PPEIntegrate ExtendStacksexttimepy

time the C stack module and type extensions versus the object chapter's Python stack implementations from PP2E.Dstruct.Basic.timer import test from PP2E.Dstruct.Basic import stackl from PP2E.Dstruct.Basic import stack2 + slice from PP2E.Dstruct.Basic import stack3 tuples from PP2E.Dstruct.Basic import stack4 append pop rept, pushes, pops, items 200, 200, 200, 200 default 200 * (600 rept, pushes, pops, items map(int, argv 1 ) except pass print 'reps d * push d+pop d+fetch d ' (rept, pushes,...

Example PPEIntegrate ExtendSwigmakefilehellolibswig

Use SWIG to integrate hellolib.c for use in Python programs. unless you've run make install SWIG . myswig hellowrap.so hellolib wrap.o (LIB) hellolib.o ld -shared hellolib wrap.o (LIB) hellolib.o -o hellowrap.so generated wrapper module code hellolib wrap.o hellolib wrap.c (LIB) hellolib.h gcc hellolib_wrap.c -c -g -I (LIB) -I (PY) Include -I (PY) (SWIG) -python -I (LIB) hellolib.i C library code (in another directory) (LIB) hellolib.o (LIB) hellolib.c (LIB) hellolib.h gcc (LIB) hellolib.c -c...

Example PPEIntegrate ExtendSwig Shadowmainsubclasspy

From number import Number sublass C++ class in Python (shadow print 'in Python add ' Number.add(self, other) def mul(self, other) print 'in Python mul ' self.data self.data * other num MyNumber(l) num.add(4) num.display() num.sub(2) num.display( ) using Python subclass of shadow class add( ) is specialized in Python num.data 99 print num.data num.display( ) Now we get extra messages out of add calls, and mul changes the C++ class's data member automatically when it assigns self.data mark toy...

Example PPEInternet CgiWeb Basicsgetfilecgi

usr bin python Display any cgi (or other) server-side file without running it. The filename can be passed in a URL param or form field e.g., Users can cut-and-paste or View source to save file locally. On IE, running the text plain version (formatted 0) sometimes pops up Notepad, but end-of-lines are not always in DOS format Netscape shows the text correctly in the browser page instead. Sending the file in text html mode works on both browsers--text is displayed in the browser response page...

Example PPEInternet CgiWeb Basicslanguagescgi

usr bin python show hello world syntax for input language name note that it uses r' ' raw strings so that ' n' in the table are left intact, and cgi.escape( ) on the string so that things like '< < ' don't confuse browsers--they are translated to valid html code any language name can arrive at this script e.g., can type in any web browser. caveats the languages list appears in both the cgi and html files--could import from a single file if selection list generated by another cgi script too...

Example PPEInternet CgiWeb Basicslanguagescommonpy

common objects shared by main and reply page scripts need change only this file to add a new language. print 'Hello World' print Hello World n puts Hello World (display Hello World) 'SmallTalk' r 'Hello World' print. System.out.println(Hello World) ', printf(Hello World n) ', cout < < Hello World < < endl ', Module languages2common contains all the data that needs to agree between pages the field name, as well as the syntax dictionary. The hellos syntax dictionary isn't quite HTML...

Example PPEInternet CgiWeb Basicslanguageshtml

< title> Languages< title> < h1> Hello World selector< h1> < P> This demo shows how to display a hello world message in various programming languages' syntax. To keep this simple, only the output command is shown (it takes more code to make a complete program in some of these languages), and only text-based solutions are given (no GUI or HTML construction logic is included). This page is a simple HTML file the one you see after pressing the button below is generated by a...

Example PPEInternet CgiWeb Basicslanguagessrccgi

usr bin python Display languages.cgi script code without running it. print Content-type text html n wrap up in html print print < H1> Source code ' s'< H1> filename print '< HR> < PRE> ' print cgi.escape(open(filename).read( )) print '< PRE> < HR> ' When we visit this script on the Web via the hyperlink or a manually typed URL, the script delivers a response to the client that includes the text of the CGI script source file. It appears as in Figure 12-25. Figure 12-25....

Example PPEInternet CgiWeb Basicsputfilecgi

usr bin python extract file uploaded by http from web browser users visit putfile.html to get the upload form page, which then triggers this script on server note this is very powerful, and very dangerous you will usually want to check the filename, etc. this will only work if file or dir is writeable a unix 'chmod 777 uploads' command may suffice file path names arrive in client's path format import cgi, string, os, sys import posixpath, dospath, macpath debugmode 0 loadtextauto 0 uploaddir...

Example PPEInternet CgiWeb Basicstestcgi

usr bin python runs on the server, prints html to create a new page executable permissions, stored in lutz public html, print Content-type text html n print < TITLE> CGI 101< TITLE> print < H1> A First CGI script< H1> print < P> Hello, CGI World < P> This file, test0.cgi, makes the same sort of page if you point your browser at it (simply replace .html with .cgi in the URL). But it's a very different kind of animal -it's an executable program that is run on the server...

Example PPEInternet CgiWeb Basicstestchtml

< HTML> < BODY> < TITLE> CGI 101< TITLE> < H1> Common input devices URL parameters< H1> < P> This demo invokes the test5.cgi server-side script again, but hardcodes input data to the end of the script's URL, within a simple hyperlink (instead of packaging up a form's inputs). Click your browser's show page source button to view the links associated with each list item below. < P> This is really more about CGI than Python, but notice that Python's cgi module...

Example PPEInternet CgiWeb Basicstesthtml

< HTML> < BODY> < TITLE> HTML 101< TITLE> < H1> A First HTML page< H1> < P> Hello, HTML World < P> < BODY> < HTML> If you point your favorite web browser to the Internet address of this file (or to its local path on your own machine), you should see a page like that shown in Figure 12-2. This figure shows the Internet Explorer browser at work other browsers render the page similarly. Figure 12-2. A simple web page from an HTML file Figure 12-2. A simple...

Example PPEInternet CgiWebfixcgipy

run fom a unix find command to automate some cgi script install steps example find . -name *.cgi -print -exec python fixcgi.py which converts all cgi scripts to unix line-feed format (needed on starship) and gives all cgi files executable mode, else won't be run do also chmod 777 PyErrata DbaseFiles *, vi Extern Email mailconfig* related fixsitename.py, PyTools fixeoln*.py, System Filetools after ungzip, untar, cp -r Cgi-Web * public html import sys, string, os fname sys.argv 1 new...

Example PPEInternet CgiWebPyMail Cgicommonhtmlpy

usr bin python generate standard page header, list, and footer HTML isolates html generation-related details in this file text printed here goes over a socket to the client, to create parts of a new web page in the web browser uses one print per line, instead of string blocks uses urllib to escape parms in url links auto from a dict, but cgi.escape to put them in html hidden fields some of the tools here are useful outside pymailcgi could also return html generated here instead of printing it,...

Example PPEInternet CgiWebPyMail Cgiexternspy

Isolate all imports of modules that live outside of the PyMailCgi PyMailCgi directory. Normally, these would come from PP2E.Internet.Email, but when I install PyMailCgi, I copy just the Cgi-Web directory's contents to public html on the server, so there is no PP2E directory on the server. Instead, I either copy the imports referenced in this file to the PyMailCgi parent directory, or tweak the dir appended to the sys.path module search path here. Because all other modules get the externals...

Example PPEInternet CgiWebPyMail CgionRoot SendLinkcgi

On 'send' click in main root window commonhtml.editpage(kind 'Write', headers 'From' mailconfig.myaddress ) No, this file wasn't truncated there's not much to see in this script, because all the action has been encapsulated in the commonhtml and externs modules. All that we can tell here is that the script calls something named editpage to generate a reply, passing in something called myaddress for its From header. That's by design -- by hiding details in utility modules, we make top-level...

Example PPEInternet CgiWebPyMail CgionSend Submitcgi

On submit in edit window--finish a write, reply, or forward import cgi, smtplib, time, string, commonhtml commonhtml.dumpstatepage(0) form cgi.FieldStorage( ) parse form input server name from module or get-style url smtpservername parms assumed to be in form or url here from commonhtml import getfield fetch value attributes From getfield(form, 'From') empty fields may not Subj getfield(form, 'Subject') caveat logic borrowed from PyMailGui date time.ctime(time.time( )) Cchdr (Cc and 'Cc s n'...

Example PPEInternet CgiWebPyMail CgionView ListLinkcgi

usr bin python On user click of message link in main selection list cgi.FieldStorage undoes any urllib escapes in the link's input parameters ( xx and '+' for spaces already undone) import cgi, rfc822, StringIO import commonhtml, loadmail from secret import decode commonhtml.dumpstatepage(0) user, pswd, site commonhtml.getstandardpopfields(form) try loadmail.loadnewmail(site, user, decode(pswd)) StringIO.StringIO(newmail int(msgnum) - 1 ) don't rfc822.Message(textfile) textfile.read( )...

Example PPEInternet CgiWebPyMail Cgipageflowtxt

pymailcgi.html > onRootViewLink.cgi > onViewListLink.cgi pick del reply fwd (fetch) > onSendSubmit.cgi > back to root > onSendSubmit.cgi > back to root Edit window, or delete+confirm Confirmation (sends smtp mail) This file simply lists all the source files in the system, using > and indentation to denote the scripts they trigger. For instance, links on the pymailcgi.html root page invoke onRootViewLink.cgi and onRootSendLink.cgi, both executable scripts. The script...

Example PPEInternet CgiWebPyMail Cgipymailcgihtml

< TITLE> PyMailCgi Main Page< TITLE> < H1 < H2 align center> A POP SMTP Email Interface< H2> < P align center> < I> Version 1.0, April 2000< I> < P> < P> < A < IMG src PyErrata ppsmall.gif align left alt Book Cover border 1 hspace 10> < A> This site implements a simple web-browser interface to POP SMTP email accounts. Anyone can send email with this interface, but for security reasons, you cannot view email unless you install the scripts with your...