Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python 2.6 Graphics Cookbook
Python 2.6 Graphics Cookbook

Python 2.6 Graphics Cookbook: Learn how to use Python’s built-in graphics capabilities to create static and animated graphics for a range of real-world purposes. Over 100 recipes take you from basic shape creation to developing interactive GUIs.

Arrow left icon
Profile Icon Michael J Ohlson
Arrow right icon
$26.09 $28.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (2 Ratings)
eBook Nov 2010 260 pages 1st Edition
eBook
$26.09 $28.99
Paperback
$48.99
eBook + Subscription
$29.99 Monthly
Arrow left icon
Profile Icon Michael J Ohlson
Arrow right icon
$26.09 $28.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (2 Ratings)
eBook Nov 2010 260 pages 1st Edition
eBook
$26.09 $28.99
Paperback
$48.99
eBook + Subscription
$29.99 Monthly
eBook
$26.09 $28.99
Paperback
$48.99
eBook + Subscription
$29.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python 2.6 Graphics Cookbook

Chapter 1. Start your Engines

In this chapter, we will cover:

  • The Shortest Python Program

  • Ensure the Python Modules are present

  • A Basic Python GUI in Tkinter

  • Make a Compiled Executable under Linux

  • Make a Compiled Executable under MS Windows

Introduction


This book is a collection of code recipes for creating and animating graphic objects using the marvelous Python language. In order to create and manipulate graphic objects, Python makes use of the Tkinter module. The prerequisite for using Python and Tkinter is obviously to have both installed. Both are free and Open Source and instructions for obtaining and installing them are abundantly available on the web. Just Google phrases like "install Python" and you will be spoilt for choice.

Our first task is to prove that Python and Tkinter are installed and working on our computer. In this book, we use Python version 2.6. Python 3.0 which came out in 2010 requires some changes in syntax that we won't be using in this book.

Let's look at some simple tests to check if Python is installed. If we download and install Python on Windows, it automatically includes Tkinter as one of the essential modules so we do not need to acquire and install it separately.

Running a shortest Python program


We need a one line Python program that will prove that the Python interpreter is installed and working on our computer platform.

How to do it...

  1. Create a folder (directory) called something like construction_work or constr for short. You will place all your Python programs inside this directory. In a text editor such as gedit on Linux or notepad on Windows. If we are working in Windows, there is a nice editor called "Context" that can be downloaded for free from http://www.contexteditor.org/ Context, that is sensitive to Python syntax and has a search-and-replace function that is useful.

  2. Type the following line:

    Print 'My wereld is "my world" in Dutch'
  3. Save this as a file named simple_1.py, inside the directory called constr.

  4. Open up an X terminal or a DOS window if you are using MS Windows.

  5. Change directory into constr - where simple_1.py is located.

  6. Type python simple_1.py and your program will execute. The result should look like the following screenshot:

  7. This proves that your Python interpreter works, your editor works, and that you understand all that is needed to run all the programs in this book. Congratulations.

    """
    Program name: simplest_1.py
    Objective: Print text to the screen.
    
    Keywords: text, simplest
    =========================
    Printed "mywereld" on terminal.
    Author:          Mike Ohlson de Fine
    
    """
    Print 'mywereld is "my world" in Dutch'

How it works...

Any instructions you type into a Linux X terminal or DOS terminal in MS Windows are treated as operating system commands. By starting these commands from within the same directory where your Python program is stored you do not have to tell the Python and operating system where to search for your code. You could store the code in another directory but you would then need to precede the program name with the path.

There's more...

Try the longer version of the same basic print instructions shown in the following program.

All the text between the """ (triple quotation marks) is purely for the sake of good documentation and record keeping. It is for the use of programmers, and that includes you. Alas, the human memory is imperfect. Bitter experience will persuade you that it is wise to provide fairly complete information as a header in your programs as well as comments inside the program.

However, in the interest of saving space and avoiding distractions, these header comments have been left out in the rest of this book.

Ensuring that the Python modules are present


Here is a slightly longer version of the previous program. However, the following modules are commanded to "report for duty" inside our program even though they are not actually used at this time: Tkinter, math, random, time, tkFont.

We need the assurance that all the Python modules we will be using later are present and accessible to Python, and therefore, to our code. Each module is a self-contained library of code functions and objects that are called frequently by the commands in your programs.

How to do it...

  1. In a text editor type the lines given in the following code.

  2. Save this as a file named simple_2.py, inside the directory called constr as we did previously.

  3. As before, open up an X terminal or a DOS window, if you are using MS Windows.

  4. Change directory into constr - where simple_1.py is located.

  5. Type python simple_2.py and our program should execute. The result should look like the following screenshot:

    This proves that your Python interpreter can access the necessary library functions it will need.

    """
    Program name: simplest_2.py
    Objective: Send more than one line of text to the screen.
    Keywords: text, simple
    ======================================
    Author:          Mike Ohlson de Fine
    """
    import Tkinter
    import math
    import random
    import time
    import tkFont
    print "======================================="
    print "A simple, apparently useless program like this does useful things:"
    print "Most importantly it checks whether your Python interpreter and "
    print "the accompanying operating system environment works"
    print " - including hardware and software"
    print "======================================"
    print " No matter how simple it is always a thrill"
    print " to get your first program to run"

How it works...

The print command is an instruction to write or print any text between quotation marks like "show these words" onto the monitor screen attached to your computer. It will also print the values of any named variables or expressions typed after print.

For example: print "dog's name:", dog_name. Where dog_name is the name of a variable used to store some data.

The print command is very useful when you are debugging a complicated sequence of code because even if the execution fails to complete because of errors, any print commands encountered before the error is reached will be respected. So by thoughtful placing of various print statements in your code, you are able to zero in on what is causing your program to crash.

There's more...

When you are writing a piece of Python code for the first time, you are often a bit unsure if your understanding of the logic is completely correct. So we would like to watch the progress of instruction execution in an exploratory way. It is a great help to be able to see that at least part of the code works. A major strength of Python is the way it takes our instructions one at a time and executes them progressively. It will only stop when the end is reached or a when programming flaw halts progress. If we have a twenty line program and only the first five lines are bug-free and the rest are unexecutable garbage, the Python interpreter will at least execute the first five. This is where the print command is a really potent little tool.

This is how you use print and the Python interpreter. When we are having trouble with our code and it just won't work and we are battling to figure out why, we can just insert print statements at various chosen points in our program. This way you can get some intermediate values of variables as your own private status reports. When we want to switch off our print watchdogs we simply type a hash (#) symbol in front, thus transforming them into passive comments. Later on, if you change your mind and want the prints to be active again you just remove the leading hash symbols.

A basic Tkinter program


Here we attempt to execute a Tkinter command inside the Python program. The Tkinter instruction will create a canvas and then draw a straight line on it.

How to do it...

  1. In a text editor, type the code given below.

  2. Save this as a file named simple_line_1.py, inside the directory called constr again.

  3. As before open up an X terminal or DOS window if you are using MS Windows.

  4. Change directory into constr - where simple_line_1.py is located.

  5. Type python simple_line_1.py and your program should execute. The command terminal result should look like the following screenshot:

  6. The Tkinter canvas output should look like the following screenshot:

  7. This proves that your Python interpreter works, your editor works, and the Tkinter module works. This is not a trivial achievement – you are definitely ready for great things. Well done.

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    from Tkinter import *
    root = Tk()
    root.title('Very simple Tkinter line')                             
    canvas_1 = Canvas(root, width=300, height=200, background="#ffffff")
    canvas_1.grid(row=0, column=0)
    
    canvas_1.create_line(10,20 ,   50,70)
    root.mainloop()
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How it works...

To draw a line, we only need to give the start point and the end point.

The start point is the first pair of numbers in canvas_1.create_line(10,20 , 50,70).In another way, the start is given by the coordinates x_start=10 and y_start=20. The end point of the line is specified by the second pair of numbers x_end=50 and y_end=70. The units of measurement are pixels. A pixel is the smallest dot that can be displayed on our screen.

For all other properties like line thickness or color, default values of the create_line() method are used.

However, should you want to change color or thickness, you just do it by specifying the settings.

Make a compiled executable under Windows and Linux


How do we create and execute a.exe file that will run a compiled version of our Python and Tkinter programs? Can we make a self-contained folder that will run on an MS Windows or Linux distribution that uses a different version of Python from the ones we use? The answers to both questions are yes and the tool to achieve this is an Open Source program called cx_Freeze. Often what we would like to do is have our working Python program on a memory stick or downloadable on a network and be able to demonstrate it to friends, colleagues, or clients without the need to download Python onto the client's system. cx_Freeze allows us to create a distributable form of our Python graphic program.

Getting ready

You will need to download cx_Freeze from http://cx-freeze.sourceforge.net/. We need to pick a version that has the same version number as the Python version we are using. Currently, there are versions available from version 2.4 up to 3.1.

How to do it under MS Windows...

  1. MS Windows : Download cx_Freeze-4.2.win32-py2.6.msi, the windows installer for Python 2.6. If we have another Python version, then we must choose the appropriate installer from http://cx-freeze.sourceforge.net/.

  2. Save and run this installer.

  3. On completion of a successful Windows install we will see a folder named cx_Freeze inside \Python26\Lib\site-packages\.

How to do it under Linux (Debian and Ubuntu)...

  1. In a terminal run the command apt-get install cx-freeze.

  2. If this does not work we may need to first install a development-capable version of Python by running the command apt-get install python-dev. Then go back and repeat step 1.

  3. Test for success by typing in python in a command terminal to invoke the Python interpreter.

  4. Then after the >>> prompt, type import cx_Freeze. If the interpreter returns a new line and the >>> prompt again, without any complaints, we have been successful.

How to compile under both Linux and MS Windows...

  1. If the file we want to package as an executable is named walking_birdy_1.py in a folder called /constr, then we prepare a special setup file as follows.

    #setup.py
    from cx_Freeze import setup, Executable
    setup(executables=[Executable("/constr/walking_birdy_1.py")])
  2. Save it as setup.py.

  3. Then, in a command terminal run

    python /constr/setup.py build
  4. We will see a lot of system compilation commands scrolling down the command terminal that will eventually stop without error messages.

  5. We will find our complete self-contained executable inside a folder named build. Under Linux, we will find it inside our home directory under /build/exe.linux-i686-2.6. Under MS Windows, we will find it inside C:\Python26\build\exe.win-py2.6.

  6. We just need to copy the folder build with all its contents to wherever we want to run our self-contained program.

How it works...

A word of caution. If we use external files like images inside our code, then the path addresses of the files must be absolute because they are coded into, or frozen, into the executable version of our Python program. There are ways of setting up search paths which can be read at http://cx-freeze.sourceforge.net/cx_Freeze.html.

For example, say we want to use some GIF images in our program and then demonstrate them on other computers. First we place a folder called, for example, /birdy_pics, onto a USB memory stick. In the original program, walking_birdy_1.py, make sure the path addresses to the images point to the /birdy_pics folder on the stick. After compilation, copy the folder build onto the USB memory stick. Now when we double-click on the executable walking_birdy_1 it can locate the images on the USB memory stick when it needs to. These files include everything that is needed for your program, and you should distribute the whole directory contents to any user who wants to run your program without needing to install Python or Tkinter.

What about py2exe?

There is another program called py2exe that will also create executables to run on MS Windows. However, it cannot create self-contained binary executables to run under Linux whereas cx_Freeze can.

Left arrow icon Right arrow icon

Key benefits

  • Create captivating graphics with ease and bring them to life using Python
  • Apply effects to your graphics using powerful Python methods
  • Develop vector as well as raster graphics and combine them to create wonders in the animation world
  • Create interactive GUIs to make your creation of graphics simpler
  • Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to accomplish the task of creation and animation of graphics as efficiently as possible

Description

Python is a great object-oriented and interactive programming language that lets you develop graphics, both static and animated, using built-in vector graphics functions that are provided with Python. Python 2.6 Graphics Cookbook is a collection of straightforward recipes and illustrative screenshots for creating and animating graphic objects using the Python language. This book makes the process of developing graphics interesting and entertaining by working in a graphic workspace without the burden of mastering complicated language definitions and opaque examples. If you choose to work through all the recipes from the beginning, you will learn to install Python and create basic programs for making lines and shapes using the built-in Tkinter module. The confusing topic of color manipulation is explored in detail using existing Python tools as well as some new tools in the recipes. Next you will learn to manipulate font size, color, and placement of text as placing text exactly where you want on a screen can be tricky because font height, inter-character spacing, and text window dimensions all interfere with each other. Then you will learn how to animate graphics, for example having more than one independent graphic object co-exist and interact using various Python methods. You will also learn how you can work with raster images, such as converting their formats using the Python Imaging Library. Next you will learn how you can combine vector images with raster images so that you can animate the raster images with ease. You will also walk through a set of recipes with the help of which you can handle and manipulate blocks of raw data that may be hundreds of megabytes in size using datastreams, files, and hard drives. You will also learn how you can use Inkscape to dismantle existing images and use parts of them for your own graphics and Python programs. At the end of the book you will learn how you can create GUIs for different purposes.

Who is this book for?

If you are looking to create animated graphics to represent real-world scenarios then this book is for you. Teachers, scholars, students, and engineers who know it is possible to make fascinating models and demonstrations but have not found a handbook that pulls it all together in one place will find what they need in this recipe bank. Basic knowledge of Python programming is required and access to the Web and Google will be useful.

What you will learn

  • Install Python and create basic programs for making lines and shapes
  • Apply different colors to your graphics using widgets and schemes available with the Tkinter module
  • Work with raster images and animate them by combining vector images with raster images
  • Optimize the storage and retrieval of graphics using hard disks, datastreams, and so on
  • Develop GUIs for different purposes to enhance your interaction with the programs
  • Move graphic objects smoothly around a screen by adding minimum delay and shift
  • Explore alternative ways and means of getting graphic shape data into Tkinter programs
  • Create beautiful patterns by setting any number of pivot points in different directions
  • Use trajectory traces to examine the history of execution required for animating specific behavior of objects

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 24, 2010
Length: 260 pages
Edition : 1st
Language : English
ISBN-13 : 9781849513852
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 24, 2010
Length: 260 pages
Edition : 1st
Language : English
ISBN-13 : 9781849513852
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 183.97
Python 2.6 Graphics Cookbook
$48.99
Python Multimedia
$50.99
Python 3 Object Oriented Programming
$83.99
Total $ 183.97 Stars icon

Table of Contents

11 Chapters
Start your Engines Chevron down icon Chevron up icon
Drawing Fundamental Shapes Chevron down icon Chevron up icon
Handling Text Chevron down icon Chevron up icon
Animation Principles Chevron down icon Chevron up icon
The Magic of Color Chevron down icon Chevron up icon
Working with Pictures Chevron down icon Chevron up icon
Combining Raster and Vector Pictures Chevron down icon Chevron up icon
Data In and Data Out Chevron down icon Chevron up icon
Exchanging Inkscape SVG Drawings with Tkinter Shapes Chevron down icon Chevron up icon
GUI Construction: Part 1 Chevron down icon Chevron up icon
GUI Construction: Part 2 Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
ltheoret Sep 08, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
clear an to the point.
Amazon Verified review Amazon
Jon Moore Sep 08, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Book is excellent, well pitched, 'Theres more' - This is a brilliant addition/ feature. - Kindle version is badly formatted when reading Code, but general reading text is fine.Amazon have charged me an extra £7.00 for something - Publisher site is cheapest by far AND has links to the code, get ready for a lot of typing if you buy from here :(
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon