The Tkinter Module

Tkinter is Python's de facto standard GUI toolkit. It's the most cross-platform GUI. Many applications are written using Tkinter because it is a very powerful and flexible tool. Maybe the most notable features are its geometry management, which is much better than standard windows, and its efficient Text and Canvas widgets. Many toolkits support as good as or better geometry management some of them are listed in this chapter . Tkinter, which stands for Tk interface, is the standard Python...

The Team Repository View

The team repository view supplants most of the Subversion status operations we looked at earlier in the chapter. It shows how the repository is different from your working copy, and how your working copy is different from the repository. It can combine those views showing all changes, or it can show only files with conflicts. It can show the aggregate changes, or it can break the differences down by revision. Open the repository view by choosing the menu item Window gt Open View gt Other. This...

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

Figure The flat plane becomes a full rotating cube

Pyopengl Glrotatef Spin

Let's say you wanted to speed up and twist your rotating cube around a bit more. It's easy to fiddle with MatrixMode, especially since you've thought ahead and included a number of variables with which to do it x,y, and z rots are the rotations on each axis xrot yrot zrot 0.0 These variables, xrot, yrot, and zrot, can be used to rotate the cube in a new way on the x-, y-, and x-axes. Do so by adding a few lines to the top of drawgraphics glLoadidentity glTranslatef 0.0, 0.0, -5.0 global rquad...

The String Data Type

A string is a sequence of characters. In Chapter 2 you learned that a string literal is a sequence of characters in quotations. Python also allows strings to be delimited by single quotes apostrophes . There's no difference just be sure to use a matching set. Strings can be stored in variables, just like numbers. Here are some examples illustrating these two forms of string literals. gt gt gt strl Hello gt gt gt str2 'spam' gt gt gt print strl, str2 Hello spam gt gt gt type strl lt type...

The Address Book as ClientServer

Back in the files topic we built a version of our address book using a dictionary. Let's reuse that example but this time we will build a client server version. Notice that the original code broke one of the good practice rules we discussed earlier I included User Interface code in my helper functions. If we were to try to use this code we would get messages from the child process mixed up with messages from the parent. We need to tweak the code slightly so that we can turn it into a reusable...

Firststep changes

In order to use the compatibility layer there are still a few changes that need to be made to your code. Many of these changes can be made by running the alter_codel module with your code as input. 1. Importing the alter_codel module handles all these changes a import Numeric - gt import numpy.oldnumeric as Numeric b import Numeric as XX - gt import numpy.oldnumeric as XX c from Numeric import lt name1 gt , lt nameN gt - gt from numpy.oldnumeric import lt name1 gt , , lt nameN gt d from Numeric...

Example AppleScript interface running on Mac

ALLOWED_SCRIPTS edit ser serial.Serial ' dev tty.pybook' print Waiting for message while True msg serial.readline .strip if msg exit print gt gt serial, bye break print Running script msg os.system osascript s.script msg print gt gt serial, Script ok The idea is that the phone client is used to choose one of the scripts to execute on the PC side. Once again, we can use Example 59 as the phone client. Again, echoing should be disabled by setting ECHO False in the client. In Python, the os.system...

generateusernamespy

Imagine we are setting up a new computer system and need to generate user-names for all of our organization's staff. We have a plain text data file UTF-8 encoding where each line represents a record and fields are colon-delimited. Each record concerns one member of the staff and the fields are their unique staff ID, forename, middle name which may be an empty field , surname, and department name. Here is an extract of a few lines from an example data users.txt data file 1601 Albert Lukas...

Indexing Lists Versus Dictionaries

A text, as we have seen, is treated in Python as a list of words. An important property of lists is that we can look up a particular item by giving its index, e.g., textl l00 . Notice how we specify a number and get back a word. We can think of a list as a simple kind of table, as shown in Figure 5-2. Figure 5-2. List lookup We access the contents of a Python list with the help of an integer index. Contrast this situation with frequency distributions Section 1.3 , where we specify a word and...

Examples 1

Hangman server 2 3 Hangman server 3 3 Text to speech MP3 player Blocking MP3 player MIDI player Sound recorder Animal sounds Binding a keycode to a callback function Key events Creating a directory for application data Retrieve the current GSM cell ID GSM location application 56 Send photos to another phone via Bluetooth 60 PySerial script running on PC 61 AppleScript interface running on Mac 72 Set the default access point SMS search using list comprehensions Input sanitization using list...

Understanding the application object lifecycle

The lifecycle of your wxPython application object begins when the application instance is created and ends just after the last application window is closed. This does not necessarily correspond to the beginning and ending of the Python script that surrounds your wxPython application. The script may choose to do some activity before creating the wxPython application, and may do further cleanup after the application MainLoop exits. All wxPython activity, however, must be performed during the life...

escape

escape escapes all nonalphanumeric characters before passing the expression to tee compiler, and returns a string with all metacharacters escaped. Here's an example in wficF the compile function fails because there are unmatched parentykses gt gt gt from re import gt gt gt strVar group gt gt gt cre compile strVar File lt console gt , line 1, in re.error Unmatched parentheses. In this example, tfe non-alphanumeric characters are escaped, so tfe compile function works gt gt gt cre compile escape...

Understanding Environment variables

Environment variables are simply a kind of storage location managed by the operating system. When you open a command prompt, you can see a list of environment variables by typing Set and pressing Enter. Figure 10-6 shows the environment variables on my system. The environment variables or at least their values will differ on your machine, so you should take a look at them. If you want to see the value of a particular environment variable, type Set VariableName such as Set USERNAME and press...

Filtering

One of the reasons to transform a time-domain signal to a frequency-domain signal is for the purpose of filtering. A filter is an operation that changes a signal. Much like filters in your kitchen sink, filters let some frequencies pass water , while stopping other frequencies large food remains . Filters are used in a variety of applications, ranging from audio to radar systems. Filters are categorized by their behavior. A filter that lets through low frequencies and stops high frequencies is...

Defining Your Own Modules

Section 2.1, The Big Picture, on page 17 explained that in order to save code for later use, you can put it in a file with a .py extension. You can then tell Python to run the code in that file, rather than typing commands in at the interactive prompt. What we didn't tell you then is that every Python file can be used as a module. The name of the module is the same as the name of the file, but without the .py extension. For example, the following function is taken from Section 2.6, Function...

Reading Tagged Corpora

Several of the corpora included with NLTK have been tagged for their part-of-speech. Here's an example of what you might see if you opened a file from the Brown Corpus with a text editor The at Fulton np-tl County nn-tl Grand jj-tl Jury nn-tl said vbd Friday nr an at inves-tigation nn of in Atlanta's np recent jj primary nn election nn produced vbd no at evidence nn '' '' that cs any dti irregularities nns took vbd place nn . . Other corpora use a variety of formats for storing part-of-speech...

Formulating Algorithms Case Study CounterControlled Repetition

To illustrate how algorithms are developed, we solve several variations of a class-averaging problem. Consider the following problem statement A class often students took a quiz. The grades integers in the range 0 -100 for this quiz are available. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem requests each of the grades, performs the averaging calculation and prints the...

Not all snakes will squish you

Chances are you were given this book for your birthday. Or possibly for Christmas. Aunty Mildred was going to give you mismatching socks that were two sizes too large and you wouldn't want to wear when you grew into them anyway . Instead, she heard someone talking about this printable book, remembered you had one of those computer-thingamabobs that you tried to show her how to use last Christmas you gave up when she started trying to talk into the mouse , and got them to print another copy....

Decision Structures and Boolean Logic

The XPath Access Mechanism

The XPath part of the solution makes accessing the elements within the XML document much easier than a traditional event-driven or even DOM-based parser. To use the XPath interface is simplicity itself. For example, to get a list of all the subelements, you need to do is access the elements property of the parent element. The each method accepts an XPath definition that in turn returns a list of all the subelements that it finds. For example, you can work through all the items using this...

The ACalculus

In Section 1.3, we pointed out that mathematical set notation was a helpful method of specifying properties P of words that we wanted to select from a document. We illustrated this with 31 , which we glossed as the set of all w such that w is an element of V the vocabulary and w has property P. It turns out to be extremely useful to add something to first-order logic that will achieve the same effect. We do this with the A-operator pronounced lambda . The A counterpart to 31 is 32 . Since we...

The Netbeans Python Debugger

As mentioned previously, the Netbeans IDE also includes a Python debugger that is derived from JeanYves Mengant's jpydbg debugger. This section will discuss how to make use of the Netbeans Python debugger along with some examples using our HockeyRoster code that was written in the previous section. If you have used a debugger in another IDE, or perhaps the Java debugger that is available for Netbeans, this debugger will feel quite familiar. The Python debugger includes many features such as...

Example Plain Text Table of Contents

Though there are many forms of documentation, plain text is perhaps the most common, as it doesn't require any additional software to view. Navigating large chunks of documentation can be difficult, though, because of the lack of links or page numbers for a table of contents. Line numbers could be used instead of page numbers, but a properly formatted table of contents can still be tedious to maintain. Consider a typical table of contents, where the title of a section is left-aligned and the...

Unpacking arguments

There's one more nifty trick involving variable arguments and keyword arguments. We've used it in some of our previous examples, but it's never too late for an explanation. Given a list or dictionary of values, we can pass those values into a function as if they were normal positional or keyword arguments. Have a look at this code def show_args arg1, arg2, arg3 THREE print arg1, arg2, arg3 arg1 ONE, arg2 TWO print Unpacking a sequence , end show_args some_args print Unpacking a dict , end...

Asynchronous IO with select and poll

When a server communicates with a client, the data it receives from the client may come in fits and spurts. If you're using forking and threading, that's not a problem. While one parallel waits for data, other parallels may continue dealing with their own clients. Another way to go, however, is to deal only with the clients that actually have something to say at a given moment. You don't even have to hear them out you just hear or, rather, read a little, and then put it back in line with the...

Deploying a Single JAR

In order to deploy an application to the Java Warehouse, it must be packaged as a single JAR file. We've already discussed packaging Jython applications into a JAR file using the Jython standalone method in Chapter 13. In this section, you will learn how to make use of the One-JAR http one-jar.sourceforge.net product to distribute client-based Jython applications. In order to get started, you will need to grab a copy of One-JAR. There are a few options available on the download site, but for...

A completely different way to set up variables

One of the most common uses for the various setup and teardown functions is to ensure certain class or module variables are available with a known value before each test method is run. py.test offers a completely different way to do this using what are known as funcargs, short for function arguments. Funcargs are basically named variables that are previously set up in a test configuration file. This allows us to separate configuration from execution of tests, and allows the funcargs to be used...

Python DB API

The quest to provide a standard way to interface to database systems drove a group of people to develop Python Database API. The Python DB API is maintained by the Database Special Interest Group DB-SIG . For more information, check out their Web site at http www.python.org sigs db-sig . The following list shows all the database modules that currently implement the Python DB API specification proposed by the DB-SIG. This means that after you understand the API, you will be able to handle, in a...

Implementing the Singleton Design Pattern

Sometimes in your applications you will have objects that by their very nature should exist at most one time and one time only a global application object would be one example. Indeed, Singletons occasionally get a bad rap for being glorified global variables, which developers frown on because it's more of a hassle to ensure that the state of that variable is correct everywhere. In IronPython, we'll store an instance of a class in a variable for reference if that instance variable is null, we...

Basic Concepts

A running program is called a process. Each process has its own system state, which includes memory, lists of open files, a program counter that keeps track of the instruction being executed, and a call stack used to hold the local variables of functions. Normally, a process executes statements one after the other in a single sequence of control flow, which is sometimes called the main thread of the process. At any given time, the program is only doing one thing. A program can create new...

Embedding the Jython Interpreter

By embedding the Jython interpreter in your own Java classes, you can run scripts from within your application, gaining control over the complete environment. That's important because few Java applications run from the command line. You can find the Jython interpreter in the class org.python.util.PythonInterpreter. You can use code like the following to initialize the Jython interpreter Properties props new Properties props.put python.home, pythonHome PythonInterpreter.initialize...

Working with Surface Objects

Loading images into Pygame is done with a simple one-liner pygame.image.load takes the file name of the image you want to load and returns a surface object, which is a container for an image. Surfaces can represent many types of image, but Pygame hides most of these details from us so we can treat them in much the same way. Once you have a surface in memory, you can draw on it, transform it, or copy it to another surface to build up an image. Even the screen is represented as a surface object....

Computing Probabilities

With the mathematical rules from probability theory one may compute the probability that a certain event happens, say the probability that you get one black ball when drawing three balls from a hat with four black balls, six white balls, and three green balls. Unfortunately, theoretical calculations of probabilities may soon become hard or impossible if the problem is slightly changed. There is a simple numerical way of computing probabilities that is generally applicable to problems with...

Event Binding 1

Happily, lambda also gives us a way to parameterize event binding. Instead of self.buttonHandler a event, button name, 1, Good stuff which wouldn't work, because there was no way to include the event argument in the argument list , we can use lambda, this way event binding -- passing the event as an argument self.button1.bind , event, arg1 button name, arg2 1, arg3 Good stuff self.buttonHandler a event, arg1, arg2, arg3 Note that event here is a variable name -- it is not a Python keyword or...

Using the interactive interpreter

When you download IronPython,33 you have two choices. You can download and install the msi installer IronPython 2 only , which includes the Python 2.5 standard library. Alternately, you can download and unpack the binary distribution that comes as a zip file. Whichever route you take, you'll have two executables, ipy.exe and ipyw.exe, which are the equivalents of the Python executables python.exe and pythonw.exe. Both are used to launch Python scripts ipy.exe launches them with a console...

A TextBased UI

In designing PokerApp we have also developed a specification for a generic Pokerlnterface class. Our interface must support the methods for displaying information setMoney, setDice, and showResult. It must also have methods that allow for input from the user wantToPlay, and chooseDice. These methods can be implemented in many different ways, producing programs that look quite different even though the underlying model, PokerApp, remains the same. Usually, graphical interfaces are much more...

The SOAP Response

Here's a possible response you might get from a SOAP server after sending it the sortList request lt xml version 1.1 encoding UTF-8 gt lt SOAP-ENV Envelope encoding lt SOAP-ENV Body lt lt ns1 sortList xmlns ns1 urn SearchSort lt lt tem gt 10 lt item gt lt return lt lt lt ns1 sortList gt lt lt SOAP-ENV Envelope gt Just as with XML-RPC, a SOAP response has the same basic structure as a SOAP request. Where the SOAP request had a list of arguments, the SOAP response has a single return value. This,...

Expressions functions and Python types

The simplest example of this is to use IronPython to evaluate individual expressions. IronPython makes a great calculator 21 So far, whenever we have executed Python code from a string we have passed in the enumeration member SourceCodeKind.Statements. This member has a sister, SourceCodeKind.Expression, that allows us to evaluate an expression and return an object. It is used in this snippet of C to evaluate a simple mathematical expression string code 2 3 5 ScriptSource source 21 You can see...

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

using Early Binding

As previously mentioned, using early binding means creating a reference to the COM component and then using that reference to interact with the component. IronPython doesn't support the standard methods of early binding that you might have used in other languages. What you do instead is create an interoperability DLL and then import that DLL into your application. The Defining an Interop DLL section of the chapter describes this process in considerably more detail. Early binding provides the...

NLTKs Regular Expression Tokenizer

The function nltk.regexp_tokenize is similar to re.findall as we've been using it for tokenization . However, nltk.regexp_tokenize is more efficient for this task, and avoids the need for special treatment of parentheses. For readability we break up the regular expression over several lines and add a comment about each line. The special x verbose flag tells Python to strip out the embedded whitespace and comments. gt gt gt text 'That U.S.A. poster-print costs 12.40 ' gt gt gt pattern r''' x set...

How do I manage the row and column headers of a grid

In a wxPython grid control, each row and column has its own label. By default, rows are given numeric labels starting with 1 and columns are given alphabetical labels starting with A and continuing to Z, which is followed by aa, ab, and so on. If you're creating a spreadsheet, this is great, but not necessary for most other applications. For something a bit less generic, wxPython provides methods to change the labels. Figure 14.3 displays a sample grid with label headers. Figure 14.3 A sample...

Python datatypes

Python boasts a rich set of built-in datatypes that you can use without importing any modules. Most of these, with the exception of the set that we introduce shortly, have syntax for including them within your code. To understand the examples in this book or to write Python yourself, you're going to need to recognize them. Table 2.1 contains a guide to all the basic datatypes and their syntaxes. Table 2.1 The built-in datatypes and their syntaxes Table 2.1 The built-in datatypes and their...

Instead of using the command line interpreter you can also use a graphical user

Figure 2.3. idle is Python's GUI interpreter. python 1.5.2 C cip Apr 13 1999, 10 51 12 msc 3 2 bit lintel on Copyright 1 amp 91-199E Stichting Mattieinatisen Centrum, Ainscertfani See Chapter 16, Development Environment, for details about using IDLE. As you can see by looking at the coding area in both Figures 2.2 and 2.3, the interpreter's primary prompt is a gt gt gt . Let's start interacting with Python by running a variation of the standard hello world program. gt gt gt print Hello Python...

Modeling the real world

There are many reasons to use a computer to simulate or model the real world. Sometimes it isn't practical to do an experiment because of time, distance, danger, or other reasons. For example, in the last chapter we simulated flipping a coin a million times. Most of us don't have time to do that with a real coin, but a computer simulation did it in seconds. Sometimes scientists want to figure out What if . . . What if an asteroid smashed into the moon We can't make a real asteroid smash into...

Redirecting output

If wxPython is controlling the standard streams, then text sent to the streams via any mechanism including a print statement or a system traceback is redirected to a separate wxPython frame. Text sent to the streams before the wxPython application begins or after it ends is, of course, processed normally. Listing 2.1, demonstrates both the application lifecycle and the stdout stderr redirection. Listing 2.1 A sample startup script showing output stream redirection def _init_ self, parent, id,...

PyArrayMultiIterType

This type provides an iterator that encapsulates the concept of broadcasting. It allows N arrays to be broadcast together so that the loop progresses in C-style contiguous fashion over the broadcasted array. The corresponding C-structure is the PyArrayMultilterObj ect whose memory layout must begin any object, obj, passed in to the PyArray_Broadcast obj function. Broadcasting is performed by adjusting array iterators so that each iterator represents the broadcasted shape and size, but has its...

A Quick Introduction to PyParsing

PyParsing makes no real distinction between lexing and parsing. Instead, it provides functions and classes to create parser elements one element for each thing to be matched. Some parser elements are provided predefined by PyParsing, others can be created by calling PyParsing functions or by instantiating PyParsing classes. Parser elements can also be created by combining other parser elements together for example, concatenating them with to form a sequence of parser elements, or or-ing them...