Python And Tkinter

Transcription

Graphical user interfaces for Python programsJohn E. GraysonPython andTkinterProgrammingMANNING

Python and Tkinter Programming

Python and TkinterProgrammingJOHN E. GRAYSONMANNINGGreenwich(74 w. long.)

For online information and ordering of this and other Manning books,go to www.manning.com. The publisher offers discounts on this bookwhen ordered in quantity. For more information, please contact:Special Sales DepartmentManning Publications Co.32 Lafayette PlaceGreenwich, CT 06830Fax: (203) 661-9018email: orders@manning.com 2000 by Manning Publications Co. All rights reserved.No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form or by means electronic, mechanical, photocopying, orotherwise, without prior written permission of the publisher.Many of the designations used by manufacturers and sellers to distinguish theirproducts are claimed as trademarks. Where those designations appear in the book,and Manning Publications was aware of a trademark claim, the designations havebeen printed in initial caps or all caps.Recognizing the importance of preserving what has been written, it is Manning’spolicy to have the books we publish printed on acid-free paper, and we exert our bestefforts to that end.Manning Publications Co.32 Lafayette PlaceGreenwich, CT 06830Copyeditor: Kristen BlackTypesetter: Dottie MarsicoCover designer: Leslie HaimesSecond corrected printing 2000Printed in the United States of America2 3 4 5 6 7 8 9 10 – CM – 03 02 01 00

To the memory of Backy, who taught me the value of language.

brief contentspreface xvspecial thanks xviiabout the reader xixabout the author xxconventions xxiabout the cover xxiiauthor online xxiiiPart I123Python 3Tkinter 12Building an application 18Part 245678910111213Basic concepts 1Displays 29Tkinter widgets 31Screen layout 77Events, bindings and callbacks 95Using classes, composites and special widgets 120Dialogs and forms 140Panels and machines 199Drawing blobs and rubber lines 237Graphs and charts 276Navigation 300The window manager 306vii

Part 3141516171819Putting it all together. 311Extending Python 313Debugging applications 329Designing effective graphics applications 338Programming for performance 348Threads and asynchronous techniques 361Distributing Tkinter applications 374Part 4Appendices 381appendix A Mapping Tk to Tkinter 383appendix B Tkinter reference 425appendix C Pmw reference: Python megawidgets 542appendix D Building and installing Python, Tkinter 610appendix E Events and keysyms 617appendix F Cursors 621appendix G References 625index 629viiiBRIEF CONTENTS

contentspreface xvspecial thanks xviiabout the reader xixabout the author xxconventions xxiabout the cover xxiiauthor online xxiiiPart I1Basic concepts 1Python 31.1 Introduction to Python programming and a feature review 3Why Python? 4,Where can Python be used? 51.2 Key data types: lists, tuples and dictionaries 5Lists 5,Tuples 7,Dictionaries 81.3 Classes 9How do classes describe objects? 9, Defining classes 9, Neat Python trick #10 9,Initializing an instance 10, Methods 10, Private and public variables andmethods 11, Inheritance 11, Multiple inheritance 11, Mixin classes 112Tkinter 122.1 The Tkinter module 12What is Tkinter? 12, What about performance? 13,Tkinter? 13, Tkinter features 142.2 Mapping Tcl/Tk to Tkinter 142.3 Win32 and UNIX GUIs 15ixHow do I use

2.4 Tkinter class hierarchy 162.5 Tkinter widget appearance 173Building an application 183.13.23.33.4Part 24Calculator example: key features 21Calculator example: source code 21Examining the application structure 27Extending the application 28Displays 29Tkinter widgets 314.1 Tkinter widget tour 31Toplevel 32, Frame 33, Label 35, Button 36, Entry 37,Radiobutton 37, Checkbutton 38, Menu 39, Message 42,Canvas 44, Scrollbar 45, Listbox 45, Scale 46Text 43,4.2 Fonts and colors 47Font descriptors 47, X Window System font descriptors 47,Setting application-wide default fonts and colors 49Colors 48,4.3 Pmw Megawidget tour 49AboutDialog 50, Balloon 50, ButtonBox 51, ComboBox 52,ComboBoxDialog 53, Counter 54, CounterDialog 55, Dialog 56,EntryField 56, Group 57, LabeledWidget 58, MenuBar 59,MessageBar 59, MessageDialog 61, NoteBookR 61, NoteBookS 62,NoteBook 63, OptionMenu 64, PanedWidget 65, PromptDialog 66,RadioSelect 66, ScrolledCanvas 67, ScrolledField 68, ScrolledFrame 69,ScrolledListbox 70, ScrolledText 70, SelectionDialog 71, TextDialog 72,TimeCounter 734.4 Creating new megawidgets 73Description of the megawidget 73,megawidget class 745Options 74,Creating theScreen layout 775.1 Introduction to layout 77Geometry management 785.2 Packer 79Using the expand option 82, Using the fill option 82, Using the padx andpady options 84, Using the anchor option 84, Using hierarchical packing 845.3 Grid 865.4 Placer 905.5 Summary 94xCONTENTS

6Events, bindings and callbacks 956.1 Event-driven systems: a review 95What are events? 96,Event propagation 97,Event types 976.2 Tkinter events 98Events 986.3 Callbacks 1026.4 Lambda expressions 103Avoiding lambdas altogether 1036.5 Binding events and callbacks 104Bind methods 104,Handling multiple bindings 1066.6 Timers and background procedures 1076.7 Dynamic callback handlers 1076.8 Putting events to work 108Binding widgets to dynamic data 108,Formatted (smart) widgets 117Data verification 111,6.9 Summary 1197Using classes, composites and special widgets 1207.1 Creating a Light Emitting Diode class 120Let’s try that again 126,What has changed? 1297.2 Building a class library 129Adding a hex nut to our class library 131,Building a MegaWidget 136Creating a switch class 133,7.3 Summary 1398Dialogs and forms 1408.1 Dialogs 141Standard dialogs 141,Tkinter variables 1528.28.38.48.58.68.78.89Data entry dialogs 142,Single-shot forms 146,A standard application framework 155Data dictionaries 165Notebooks 172Browsers 175Wizards 184Image maps 191Summary 198Panels and machines 1999.1 Building a front panel 1999.2 Modularity 201CONTEN TSxi

9.39.49.59.6Implementing the front panel 201GIF, BMP and overlays 215And now for a more complete example 220Virtual machines using POV-Ray 232And now for something completely different. #10 The Example 2339.7 Summary 23610Drawing blobs and rubber lines 23710.1 Drawing on a canvas 238Moving canvas objects 24310.210.310.410.510.610.710.811A more complete drawing program 244Scrolled canvases 251Ruler-class tools 254Stretching canvas objects 258Some finishing touches 262Speed drawing 271Summary 275Graphs and charts 27611.1 Simple graphs 27611.2 A graph widget 279Adding bargraphs 286,Pie charts 28911.3 3-D graphs 29211.4 Strip charts 29611.5 Summary 29812Navigation 30012.112.212.312.412.512.613The window manager 30613.113.213.313.4xiiIntroduction: navigation models 300Mouse navigation 301Keyboard navigation: “mouseless navigation” 301Building navigation into an application 302Image maps 305Summary 305What is a window manager? 306Geometry methods 307Visibility methods 308Icon methods 309CONTENTS

13.5 Protocol methods 30913.6 Miscellaneous wm methods 310Part 314Putting it all together. 311Extending Python 31314.1 Writing a Python extension 31314.2 Building Python extensions 316Linking an extension statically in UNIX 316, Linking an extensionstatically in Windows 317, Building a dynamic module in UNIX 317,Building a dynamic module in Windows 318, Installing dynamicmodules 319, Using dynamic modules 31914.314.414.514.614.714.815Debugging applications 32915.115.215.315.415.515.615.716Using the Python API in extensions 319Building extensions in C 320Format strings 321Reference counts 324Embedding Python 325Summary 328Why print statements? 329A simple example 330How to debug 333A Tkinter explorer 334pdb 336IDLE 336DDD 337Designing effective graphics applications 33816.1 The elements of good interface design 33916.2 Human factors 342Choosing fonts 343, Use of color in graphical user interfaces 344,Size considerations 34616.3 Alternative graphical user interfaces 34616.4 Summary 34717Programming for performance 34817.1 Everyday speedups 348Program organization 349, Using the Python optimizer 350, Examining code 350CONTEN TSxiii

17.2 Tkinter performance 350Keep it short! 350, Eliminate local variables 351,Fast initialization 352, Throttling events 352Keep it simple 351,17.3 Python techniques 352Importing modules 353, Concatenating strings 353, Getting nestedloops right 354, Eliminate module references 354, Use local variables 355,Using exceptions 356, Using map, filter and reduce 35617.4 Application profiling 35717.5 Python extensions 35917.6 Summary 36018Threads and asynchronous techniques 36118.1 Threading 361Non-GUI threads 362,GUI threads 36518.2 “after” processing 36918.3 Summary 37319Distributing Tkinter applications 37419.119.219.319.4Part 4General issues in distributing applications 374Distributing UNIX applications 375Distributing Win32 applications 376Python distribution tools 379Appendices 381appendix A Mapping Tk to Tkinter 383appendix B Tkinter reference 425appendix C Pmw reference: Python megawidgets 542appendix D Building and installing Python, Tkinter 610appendix E Events and keysyms 617appendix F Cursors 621appendix G References 625index 629xivCONTENTS

prefaceI first encountered Python in 1993 when I joined a small company in Rhode Island. Their primary product was a GUI-builder for X/Motif that generated code for C, C , Ada and Python. Iwas tasked with extending the object-oriented interface for X/Motif and Python. In the past I’dbecome skeptical about the use of interpretive languages, so I began the task with little excitement. Two days later I was hooked. It was easy to develop interfaces that would have taken muchmore time and code to develop in C. Soon after, I began to choose interfaces developed using thePython interface in preference to compiled C code.After I left the company in Rhode Island, I began to develop applications using Tkinter,which had become the preeminent GUI for Python. I persuaded one company, where I wasworking on contract, to use Python to build a code-generator to help complete a huge projectthat was in danger of overrunning time and budget. The project was a success. Four years laterthere are many Python programmers in that company and some projects now use Tkinter andPython for a considerable part of their code.It was this experience, though, that led me to start writing this book. Very little documentation was available for Tkinter in the early days. The Tkinter Life Preserver was the first documentthat helped people pull basic information together. In 1997 Fredrik Lundh released some excellent documentation for the widget classes on the web, and this has served Tkinter programmerswell in the past couple of years. One of the problems that I saw was that although there were several example programs available (the Python distribution contains several), they were mostly briefin content and did not represent a framework for a full application written with Tkinter. Ofcourse, it is easy to connect bits of code together to make it do more but when the underlyingarchitecture relies on an interpreter it is easy to produce an inferior product, in terms of execution speed, aesthetics, maintainability and extensibility.So, one of the first questions that I was asked about writing Tkinter was “How do I make anXXX?” I’d usually hand the person a chunk of code that I’d written and, like most professionalprogrammers, they would work out the details. I believe strongly that learning from full, workingexamples is an excellent way of learning how to program in a particular language and to achieveparticular goals.When I was training in karate, we frequently traveled to the world headquarters of Shukokai, in New Jersey, to train with the late Sensei Shigeru Kimura. Sensei Kimura often told us “Ixv

can’t teach you how to do this (a particular technique)—you have to steal it.” My approach tolearning Tkinter is similar. If someone in the community has solved a problem, we need to stealit from them. Now, I am not suggesting that we infringe copyright and professional practice! Isimply mean you should learn from whatever material is available. I hope that you will use theexamples in the book as a starting point for your own creations. In a small number of cases I haveused code or the ideas of other programmers. If this is the case I have given the original author anappropriate acknowledgment. If you use one of these pieces of code, I’d appreciate it if you wouldalso acknowledge the original author. After all, what we “steal” has more value than what we produce ourselves—it came from the Sensei!I was impressed by the format of Douglas A. Young’s The X Window System: Programmingand Applications with Xt. It is a little old now, but it had a high proportion of complete codeexamples, some of which made excellent templates upon which new applications could be built.Python and Tkinter Programming has some parallels in its layout. You will find much longerexamples than you may be accustomed to in other programming books. I hope that many of theexamples will be useful either as templates or as a source of inspiration for programmers whohave to solve a particular problem.One side effect of presenting complete examples as opposed to providing code fragments isthat you will learn a great deal about my style of programming. During the extensive reviews forPython and Tkinter Programming some of the reviewers suggested alternate coding patterns forsome of the examples. Wherever possible, I incorporated their suggestions, so that the examplesnow contain the programming styles of several people. I expect that you will make similarimprovements when you come to implement your own solutions.I hope that you find Python and Tkinter Programming useful. If it saves you even a couple ofhours when you have an application to write, then it will have been worth the time spent readingthe book.xviPREFACE

special thanksWriting Python and Tkinter Programming has been the collective effort of many people. Each ofthese persons contributed their time, expertise and effort to help make the book more effective.Many of the words are theirs and not mine—the book is now better.I want to thank the team of technical reviewers: Fred L. Drake, Robin Friedrich, AlanGauld, Bob Gibson, Lynn Grande, Doug Hellmann, Garrett G. Hodgson, Paul Kendrew,Andrew M. Kuchling, Cameron Laird, Gregory A. Landrum, Ivan Van Laningham, Burt Leavenworth, Ken McDonald, Frank McGeough, Robert Meegan, William Peloquin, Robert J. Robertsand Guido van Rossum. They provided detailed comments that resulted in significant improvements to the book’s content, focus and accuracy.Some of the code examples were derived from code written by others. I want to thank theseauthors for agreeing to allow me to use their code in this book.Doug Hellman wrote an excellent module for Pmw, GUIAppD.py, which I adapted as AppShell.py and used for many examples within the book. Doug agreed that I could use the code. Ifyou find AppShell.py useful in your applications, please acknowledge the original author of thiswork.Konrad Hinsen wrote TkPlotCanvas.py, which was intended to be used with NumPy,which uses extension modules optimized for numerical operations. I adapted it to run withoutNumPy and also added some additional graphical capabilities. Again, if you find it useful, pleaseacknowledge Konrad Hinsen.The Tree and Node classes used in chapter 8 are derived from code released by OpenChemfor inclusion within their Open Source project. You might want to look at any future releasesfrom this organization, since the tree-widget examples presented in this book are limited in theircapability.Appendix B uses the man pages for Tk as a starting point for documenting Tkinter. Thecopyright owners, the Regents of the University of California and Sun Microsystems allow derivative works to be made, provided that the original copyright is acknowledged.I also want to thank Gordon Smith at General Dynamics for having confidence in the useof Python and Tkinter in some of the projects for which he was responsible; observing their usein real-world applications is one of the factors that prompted me to begin the task of writing thexvii

book. I was able to test some of the draft chapters by giving them to his staff and intern studentsto solve some of their programming tasks.Next, I want to thank everyone at Manning Publications who turned my ideas into a book.I had many long conversations with the publisher, Marjan Bace, who led me through the somewhat complex task of writing a book that is going to be useful to its readers. Ted Kennedy coordinated the review process which produced much constructive criticism. Mary Piergies took careof the production of the book with Kristen Black, the copyeditor, and Dottie Marsico, the typesetter, who took my crude attempts to use FrameMaker and gave the book the professional edgeit needed. Doug Hellman did a fine technical edit and corrected many code problems found inthe final typeset copy.Finally, I’d like to thank my wife, Allison, and my children, Nina, Chris, Jeff and Alana, forunderstanding that it wasn’t so much losing a spouse and father but gaining an author.xviiiS P EC IA L THAN KS

about the readerPython and Tkinter Programming is intended for programmers who already know Python or whoare learning Python (perhaps using Manning’s Quick Python as their guide) who wish to addgraphical user interfaces (GUIs) to their applications. Because Python and Tkinter Programmingpresents many fully functional examples with lots of code annotations, experienced programmerswithout Python expertise will find the book helpful in using Python and Tkinter to solve immediate problems.The book may also be used by Tcl/Tk script programmers as a guide to converting fromTcl/Tk to Python and Tkinter. However, I do not intend to get into a philosophical discussionabout whether that would be a proper thing to do—I’m biased!xix

about the authorJohn Grayson is a consultant specializing in graphical user interfaces (GUIs). He has been supporting application design at a large U.S. communications company for several years, designinginnovative interfaces and introducing Python and Object-Oriented Programming (OOP) to traditional development methods. Elsewhere, he has delivered real-world applications written inPython and Tkinter for commercial use.He holds a Bachelor's degree in Applied Biology and a Ph.D. in Molecular Biology—butthat has never been an impediment (especially because 90 percent of his thesis covered computermodeling of enzyme behavior).Before specializing in user interfaces, he was an operating-system specialist and was laterinstrumental in developing support methodologies for UNIX at Stratus Computer, Inc., he builtan F77 compiler and UNIX porting tools at Pacer Software, Inc. and he was an operating-systemspecialist at Prime Computer, Inc. both in the United States and Great Britain.xx

conventionsExample code plays a very important role in Python and Tkinter Programming. Many programming books feature short, simple examples which illustrate one or two points very well—butreally do little. In this book, the examples may be adapted for your own applications or even usedjust as they are. Most of the examples are intended to be run stand-alone as opposed to being runinteractively. Most examples include markers in the body of the code which correspond to explanations which follow. For example:def mouseDown(self, event):self.currentObject Noneself.lastx self.startx self.canvas.canvasx(event.x)self.lasty self.starty self.canvas.canvasy(event.y)if not self.currentFunc:self.selObj self.canvas.find mconfig(self.selObj, width 2)12self.canvas.lift(self.selObj)Code comments1 The mouseDown method deselects any currently selected object. The event returns x and y coordinates for the mouse-click as screen coordinates. The canvasx and canvasy methods of theCanvas widget .2 If no drawing function is selected, we are in select mode and we search to locate the nearestobject on the canvas and select it. This method of .Occasionally, I have set portions of code in bold code font to highlight code which is ofspecial importance in the code example.In a number of examples where the code spans several pages I have interspersed code explanations within the code sequence so that the explanatory text appears closer to the code that isbeing explained. The marker numbering is continuous within any given example.xxi

about the coverThe cover illustration of this book is from the 1805 edition of Sylvain Maréchal’s four-volumecompendium of regional dress customs. This book was first published in Paris in 1788, one yearbefore the French Revolution. Its title alone required no fewer than 30 words:Costumes Civils actuels de tous les peuples connus dessinés d’après nature gravés etcoloriés, accompagnés d’une notice historique sur leurs coutumes, moeurs, religions,etc., etc., redigés par M. Sylvain MaréchalThe four volumes include an annotation on the illustrations: “gravé à la manière noire parMixelle d’après Desrais et colorié.” Clearly, the engraver and illustrator deserved no more than tobe listed by their last names—after all they were mere technicians. The workers who colored eachillustration by hand remain nameless.The colorful variety of this collection reminds us vividly of how culturally apart the world’stowns and regions were just 200 years ago. Dress codes have changed everywhere and the diversity by region, so rich at the time, has faded away. It is now hard to tell the inhabitant of one continent from another. Perhaps we have traded cultural diversity for a more varied personal life—certainly a more varied and exciting technological environment. At a time when it is hard to tellone computer book from another, Manning celebrates the inventiveness and initiative of thecomputer business with book covers based on the rich diversity of regional life of two centuriesago, brought back to life by Maréchal’s pictures. Just think, Maréchal’s was a world so differentfrom ours people would take the time to read a book title 30 words long.xxii

author onlinePurchase of Python and Tkinter Programming includes free access to a private Internet forumwhere you can make comments about the book, ask technical questions and receive help fromthe author and other Python and Tkinter users. To access the forum, point your web browser towww.manning.com/grayson. There you will be able to subscribe to the forum. This site also provides information on how to access the forum once you are registered, what kind of help is available and the rules of conduct on the forum.All source code for the examples presented in this book is available from the Mannng website. The URL www.manning.com/grayson includes a link to the source code files.xxiii

P ART1Basic conceptsIn part 1, I’ll introduce Python, Tkinter and application programming. Since I assume you’realready somewhat familiar with Python, chapter 1 is intended to illustrate the most important featuresof the language that will be used throughout the book. Additionally, I’ll discuss features of Python’ssupport for object-oriented programming so that those of you familiar with C or Java can understand how your experience may be applied to Python.Chapter 2 quickly introduces Tkinter and explains how it relates to Tcl/Tk. You will find detailsof mapping Tk to Tkinter, along with a brief introduction to the widgets and their appearance.Chapter 3 illustrates application development with Tkinter using two calculator examples. Thefirst is a simple no-frills calculator that demonstrates basic principles. The second is a partially finishedapplication that shows you how powerful applications may be developed using Python’s and Tkinter’scapabilities.

C HAPT ER1Python1.1 Introduction to Python programming and a feature review1.2 Key data types: lists, tuples and dictionaries 51.3 Classes 93This chapter defines the key features of Python that make the language ideal for rapid prototyping of systems and for fully-functional applications. Python and Tkinter Programming isnot intended to be a learning resource for beginning Python programmers; several otherpublications are better-suited to this task: Quick Python, Learning Python, ProgrammingPython, Internet Programming in Python and The Python Pocket Reference are all excellenttexts. Further information is provided in the “References” section at the end of this book. Inthis chapter, the key features of Python will be highlighted in concise examples of code toillustrate some of the building blocks that will be used in examples throughout the book.1.1 Introduction to Python programming anda feature reviewAs stated earlier, this book is not intended to be used to learn Python basics directly. Programmers experienced in other languages will be able to analyze the examples and discoverthe key points to programming in Python. However, if you are relatively new to programming generally, then learning Python this way will be a tough, upward struggle.3

This chapter is really not necessary for most readers, then, since the material will alreadybe familiar. Its purpose is to provide a refresher course for readers who worked with Pythonin the early days and a map for Tcl/Tk programmers and those readers experienced with otherlanguages.Readers unfamiliar with object-oriented programming (OOP) may find section 1.3 useful as an introduction to OOP as it is implemented in Python. C or Java programmers whoneed to see how Python’s classes operate will benefit as well.I’m not going to explain the reasons why Python was developed or when, since this information is covered in every other Python book very well. I will state that Guido van Rossum,Python’s creator, has been behind the language since he invented it at Stichting MathematischCentrum (CWI) in Amsterdam, The Nederlands, around 1990; he is now at the Corporationfor National Research Initiatives (CNRI), Reston, Virginia, USA. The fact that one person hastaken control of the growth of the language has had a great deal to do with its stability andelegance, although Guido will be the first to thank all of the people who have contributed, inone way or another, to the language’s development.Perhaps more important than any of the above information is the name of the language.This language has nothing to do with snakes. Python is named after Monty Python’s Flying Circus, the BBC comedy series which was produced from 1969 to 1974. Like many university students around 1970, I was influenced by Monty Python, so when I started writing this book Icould not resist the temptation to add bits of Python other than the language. Now, all of youthat skipped the boring beginning bit of this book, or decided that you didn’t need to read thisparagraph are in for a surprise. Scattered through the examples you’ll find bits of Python. Ifyou have never experienced Monty Python, then I can only offer the following advice: if something about the example looks weird, it’s probably Python. As my Yugoslavian college friendused to say “You find that funny”?1.1.1Why Python?Several key features make Python an ideal language for a wide range of applications. AddingTkinter to the mix widens the possibilities dramatically. Here are some of the highlights thatmake Python what it is: Automatic compile to bytecodeHigh-level data types and operationsPortability across architecturesWide (huge) range of supported extensionsObject-oriented modelIdeal prototyping systemReadable code with a distinct C-like quality supports maintenanceEasy to extend in C and C and embed in applicationsLarge library of contributed applications and toolsExcellent documentationYou might notice that I did not mention an interpreter explicitly. One feature of Pythonis that it is a bytecode engine written in C. The extension modules are written in C. With alittle care in the way you design your code, most of your code will run using compiled C sincemany operations are built into the system. The remaining code will run in the bytecode engine.4CHAPTER 1PYTHON

The result is a system that may be used as a scripting language to develop anything from somesystem administration scripts all the way to a complex GUI-based application (using database,client/server, CORBA or other techniques).1.1.2Where can Python be used?Knowing where Python can be used is best understood by learning where it might not be thebest choice. Regardless of what I just said about the bytecode engine, Python has an interpretive nature, so if you can’t keep within the C-extensions, there has to be a performance penalty. Therefore, real-time applications for high-speed events would be a poor match. A set ofextensions to Python have been developed specifically for numerical programming (see“NumPy” on page 626). These extensions help support compute-bound applications, butPython is not the best choice for huge computation-intensive applications unless time isn’t afactor. Similarly, graphics-intensive applications which involve real-time observation are not agood match (but see “Speed drawing” on page 271 for an example of what can be done).1.2 Key data types: lists, tuples and dictionariesThree key data types give Python the power to produce effective applications: two sequenceclasses—lists and tuples—and a mapping class—dictionaries. When they are used together,they can deliver surprising power in a few lines of code.Lists and tuples have a lot in common. The major difference is that the elements of a listcan be modified in place but a tuple is immutable: you have to deconstruct and then reconstructa tuple to change individual elements. There are several good reasons why we should care aboutthis distinction; if you want to use a tuple as the key to a dictionary, it’s good

working on contract, to use Python to build a code-generator to help complete a huge project that was in danger of overrunning time and budget. The project was a success. Four years later there are many Python programmers in that company and some projects now use Tkinter and