Tài liệu Python and tkinter programming

  • Số trang: 684 |
  • Loại file: PDF |
  • Lượt xem: 235 |
  • Lượt tải: 0
minhminh

Đã đăng 411 tài liệu

Mô tả:

Graphical user interfaces for Python programs John E. Grayson Python and Tkinter Programming MANNING Python and Tkinter Programming Python and Tkinter Programming JOHN E. GRAYSON MANNING Greenwich (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 book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. 32 Lafayette Place Greenwich, CT 06830 Fax: (203) 661-9018 email: orders@manning.com ©2000 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Manning Publications Co. 32 Lafayette Place Greenwich, CT 06830 Copyeditor: Kristen Black Typesetter: Dottie Marsico Cover designer: Leslie Haimes Second corrected printing 2000 Printed in the United States of America 2 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 contents preface xv special thanks xvii about the reader xix about the author xx conventions xxi about the cover xxii author online xxiii Part I 1 2 3 Python 3 Tkinter 12 Building an application 18 Part 2 4 5 6 7 8 9 10 11 12 13 Basic concepts 1 Displays 29 Tkinter widgets 31 Screen layout 77 Events, bindings and callbacks 95 Using classes, composites and special widgets 120 Dialogs and forms 140 Panels and machines 199 Drawing blobs and rubber lines 237 Graphs and charts 276 Navigation 300 The window manager 306 vii Part 3 14 15 16 17 18 19 Putting it all together... 311 Extending Python 313 Debugging applications 329 Designing effective graphics applications 338 Programming for performance 348 Threads and asynchronous techniques 361 Distributing Tkinter applications 374 Part 4 Appendices 381 appendix A Mapping Tk to Tkinter 383 appendix B Tkinter reference 425 appendix C Pmw reference: Python megawidgets 542 appendix D Building and installing Python, Tkinter 610 appendix E Events and keysyms 617 appendix F Cursors 621 appendix G References 625 index 629 viii BRIEF CONTENTS contents preface xv special thanks xvii about the reader xix about the author xx conventions xxi about the cover xxii author online xxiii Part I 1 Basic concepts 1 Python 3 1.1 Introduction to Python programming and a feature review 3 Why Python? 4, Where can Python be used? 5 1.2 Key data types: lists, tuples and dictionaries 5 Lists 5, Tuples 7, Dictionaries 8 1.3 Classes 9 How do classes describe objects? 9, Defining classes 9, Neat Python trick #10 9, Initializing an instance 10, Methods 10, Private and public variables and methods 11, Inheritance 11, Multiple inheritance 11, Mixin classes 11 2 Tkinter 12 2.1 The Tkinter module 12 What is Tkinter? 12, What about performance? 13, Tkinter? 13, Tkinter features 14 2.2 Mapping Tcl/Tk to Tkinter 14 2.3 Win32 and UNIX GUIs 15 ix How do I use 2.4 Tkinter class hierarchy 16 2.5 Tkinter widget appearance 17 3 Building an application 18 3.1 3.2 3.3 3.4 Part 2 4 Calculator example: key features 21 Calculator example: source code 21 Examining the application structure 27 Extending the application 28 Displays 29 Tkinter widgets 31 4.1 Tkinter widget tour 31 Toplevel 32, Frame 33, Label 35, Button 36, Entry 37, Radiobutton 37, Checkbutton 38, Menu 39, Message 42, Canvas 44, Scrollbar 45, Listbox 45, Scale 46 Text 43, 4.2 Fonts and colors 47 Font descriptors 47, X Window System font descriptors 47, Setting application-wide default fonts and colors 49 Colors 48, 4.3 Pmw Megawidget tour 49 AboutDialog 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 73 4.4 Creating new megawidgets 73 Description of the megawidget 73, megawidget class 74 5 Options 74, Creating the Screen layout 77 5.1 Introduction to layout 77 Geometry management 78 5.2 Packer 79 Using the expand option 82, Using the fill option 82, Using the padx and pady options 84, Using the anchor option 84, Using hierarchical packing 84 5.3 Grid 86 5.4 Placer 90 5.5 Summary 94 x CONTENTS 6 Events, bindings and callbacks 95 6.1 Event-driven systems: a review 95 What are events? 96, Event propagation 97, Event types 97 6.2 Tkinter events 98 Events 98 6.3 Callbacks 102 6.4 Lambda expressions 103 Avoiding lambdas altogether 103 6.5 Binding events and callbacks 104 Bind methods 104, Handling multiple bindings 106 6.6 Timers and background procedures 107 6.7 Dynamic callback handlers 107 6.8 Putting events to work 108 Binding widgets to dynamic data 108, Formatted (smart) widgets 117 Data verification 111, 6.9 Summary 119 7 Using classes, composites and special widgets 120 7.1 Creating a Light Emitting Diode class 120 Let’s try that again 126, What has changed? 129 7.2 Building a class library 129 Adding a hex nut to our class library 131, Building a MegaWidget 136 Creating a switch class 133, 7.3 Summary 139 8 Dialogs and forms 140 8.1 Dialogs 141 Standard dialogs 141, Tkinter variables 152 8.2 8.3 8.4 8.5 8.6 8.7 8.8 9 Data entry dialogs 142, Single-shot forms 146, A standard application framework 155 Data dictionaries 165 Notebooks 172 Browsers 175 Wizards 184 Image maps 191 Summary 198 Panels and machines 199 9.1 Building a front panel 199 9.2 Modularity 201 CONTEN TS xi 9.3 9.4 9.5 9.6 Implementing the front panel 201 GIF, BMP and overlays 215 And now for a more complete example 220 Virtual machines using POV-Ray 232 And now for something completely different... #10 The Example 233 9.7 Summary 236 10 Drawing blobs and rubber lines 237 10.1 Drawing on a canvas 238 Moving canvas objects 243 10.2 10.3 10.4 10.5 10.6 10.7 10.8 11 A more complete drawing program 244 Scrolled canvases 251 Ruler-class tools 254 Stretching canvas objects 258 Some finishing touches 262 Speed drawing 271 Summary 275 Graphs and charts 276 11.1 Simple graphs 276 11.2 A graph widget 279 Adding bargraphs 286, Pie charts 289 11.3 3-D graphs 292 11.4 Strip charts 296 11.5 Summary 298 12 Navigation 300 12.1 12.2 12.3 12.4 12.5 12.6 13 The window manager 306 13.1 13.2 13.3 13.4 xii Introduction: navigation models 300 Mouse navigation 301 Keyboard navigation: “mouseless navigation” 301 Building navigation into an application 302 Image maps 305 Summary 305 What is a window manager? 306 Geometry methods 307 Visibility methods 308 Icon methods 309 CONTENTS 13.5 Protocol methods 309 13.6 Miscellaneous wm methods 310 Part 3 14 Putting it all together... 311 Extending Python 313 14.1 Writing a Python extension 313 14.2 Building Python extensions 316 Linking an extension statically in UNIX 316, Linking an extension statically in Windows 317, Building a dynamic module in UNIX 317, Building a dynamic module in Windows 318, Installing dynamic modules 319, Using dynamic modules 319 14.3 14.4 14.5 14.6 14.7 14.8 15 Debugging applications 329 15.1 15.2 15.3 15.4 15.5 15.6 15.7 16 Using the Python API in extensions 319 Building extensions in C++ 320 Format strings 321 Reference counts 324 Embedding Python 325 Summary 328 Why print statements? 329 A simple example 330 How to debug 333 A Tkinter explorer 334 pdb 336 IDLE 336 DDD 337 Designing effective graphics applications 338 16.1 The elements of good interface design 339 16.2 Human factors 342 Choosing fonts 343, Use of color in graphical user interfaces 344, Size considerations 346 16.3 Alternative graphical user interfaces 346 16.4 Summary 347 17 Programming for performance 348 17.1 Everyday speedups 348 Program organization 349, Using the Python optimizer 350, Examining code 350 CONTEN TS xiii 17.2 Tkinter performance 350 Keep it short! 350, Eliminate local variables 351, Fast initialization 352, Throttling events 352 Keep it simple 351, 17.3 Python techniques 352 Importing modules 353, Concatenating strings 353, Getting nested loops right 354, Eliminate module references 354, Use local variables 355, Using exceptions 356, Using map, filter and reduce 356 17.4 Application profiling 357 17.5 Python extensions 359 17.6 Summary 360 18 Threads and asynchronous techniques 361 18.1 Threading 361 Non-GUI threads 362, GUI threads 365 18.2 “after” processing 369 18.3 Summary 373 19 Distributing Tkinter applications 374 19.1 19.2 19.3 19.4 Part 4 General issues in distributing applications 374 Distributing UNIX applications 375 Distributing Win32 applications 376 Python distribution tools 379 Appendices 381 appendix A Mapping Tk to Tkinter 383 appendix B Tkinter reference 425 appendix C Pmw reference: Python megawidgets 542 appendix D Building and installing Python, Tkinter 610 appendix E Events and keysyms 617 appendix F Cursors 621 appendix G References 625 index 629 xiv CONTENTS preface I 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. I was tasked with extending the object-oriented interface for X/Motif and Python. In the past I’d become 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 much more time and code to develop in C. Soon after, I began to choose interfaces developed using the Python 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 was 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 Python 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 document that 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 programmers well 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 brief in content and did not represent a framework for a full application written with Tkinter. Of course, it is easy to connect bits of code together to make it do more but when the underlying architecture 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 an XXX?” I’d usually hand the person a chunk of code that I’d written and, like most professional programmers, they would work out the details. I believe strongly that learning from full, working examples is an excellent way of learning how to program in a particular language and to achieve particular 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 “I xv can’t teach you how to do this (a particular technique)—you have to steal it.” My approach to learning Tkinter is similar. If someone in the community has solved a problem, we need to steal it from them. Now, I am not suggesting that we infringe copyright and professional practice! I simply mean you should learn from whatever material is available. I hope that you will use the examples in the book as a starting point for your own creations. In a small number of cases I have used code or the ideas of other programmers. If this is the case I have given the original author an appropriate acknowledgment. If you use one of these pieces of code, I’d appreciate it if you would also 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: Programming and Applications with Xt. It is a little old now, but it had a high proportion of complete code examples, 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 longer examples than you may be accustomed to in other programming books. I hope that many of the examples will be useful either as templates or as a source of inspiration for programmers who have to solve a particular problem. One side effect of presenting complete examples as opposed to providing code fragments is that you will learn a great deal about my style of programming. During the extensive reviews for Python and Tkinter Programming some of the reviewers suggested alternate coding patterns for some of the examples. Wherever possible, I incorporated their suggestions, so that the examples now contain the programming styles of several people. I expect that you will make similar improvements 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 of hours when you have an application to write, then it will have been worth the time spent reading the book. xvi PREFACE special thanks Writing Python and Tkinter Programming has been the collective effort of many people. Each of these 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, Alan Gauld, 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. Roberts and 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 these authors 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. If you find AppShell.py useful in your applications, please acknowledge the original author of this work. 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 without NumPy and also added some additional graphical capabilities. Again, if you find it useful, please acknowledge Konrad Hinsen. The Tree and Node classes used in chapter 8 are derived from code released by OpenChem for inclusion within their Open Source project. You might want to look at any future releases from this organization, since the tree-widget examples presented in this book are limited in their capability. Appendix B uses the man pages for Tk as a starting point for documenting Tkinter. The copyright 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 use of Python and Tkinter in some of the projects for which he was responsible; observing their use in real-world applications is one of the factors that prompted me to begin the task of writing the xvii book. I was able to test some of the draft chapters by giving them to his staff and intern students to 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 care of 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 edge it needed. Doug Hellman did a fine technical edit and corrected many code problems found in the final typeset copy. Finally, I’d like to thank my wife, Allison, and my children, Nina, Chris, Jeff and Alana, for understanding that it wasn’t so much losing a spouse and father but gaining an author. xviii S P EC IA L THAN KS about the reader Python and Tkinter Programming is intended for programmers who already know Python or who are learning Python (perhaps using Manning’s Quick Python as their guide) who wish to add graphical user interfaces (GUIs) to their applications. Because Python and Tkinter Programming presents many fully functional examples with lots of code annotations, experienced programmers without 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 from Tcl/Tk to Python and Tkinter. However, I do not intend to get into a philosophical discussion about whether that would be a proper thing to do—I’m biased! xix
- Xem thêm -