Size: 22425
Comment:
|
Size: 22447
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 7: | Line 7: |
[attachment:cover.jpg] |
活学活用wxPython
[attachment:cover.jpg] TableOfContents
前言
关于 Harri Pasanen 和 Robin Dunn 以及wxPython的传奇故事确切的开始时间是1995年。本书的合著者之一,Robin 写下了下面这段关于wxPython 的文字,而我们决定让故事由参与者自己来讲述,而不是籍由旁人加以引述:
- 1995年,我所进行的一个项目需要在HP-UX系统上部署一个图形用户界面,但我的老板却同时希望在几周后的一个内部展示会上通过Windows3.1掌上电脑来进行一些演示。因此,我开始搜寻跨平台的C++ GUI开发包来进行原型开发。在那个时候,因为没有Google,要完成这样的工作实非易事。但我还是发现了一些商业化的可选开发包(今天已经无一幸存)和大量的免费开发包。
当我正在评估分析哪个免费开发包符合当前的紧急需求,并决定哪个商业产品能够满足我们的长期需求时,我偶然看到了 wxWidgets 网站的术语“Python绑定”(这里“绑定”一词指Python语言和wxWidgets开发包之间的联系。)由于对如何将软件开发包“绑定”到爬虫动物(在此之前,我从来没有听说过Python语言)充满好奇,我顺着这个链接一个个的点击,直到看到“Python 1.2 入门文档”。三个小时后,我从当地的C++倡导者变成了Python的传播者,不断叨扰周边的开发者,向他们展示我的最新发现。
我开始和芬兰的Harri Pasanen一起致力于推进Python和wxWidgets的绑定(在Edward Zimmerman的协助下,最终形成了众所周知的wxPython 0.2),而不是继续我的原型开发。发行声明的邮件列表归档于[http://www.google.com/groups?selm=PA.95Jul27032244%40ok.tekla.fi&oe=UTF-8] 我们使它的功能强大到多足以让我能够用Python为老板建造一个原型。但是wxPython的维护和改进工作却是一个噩梦,因为每件事情(包括C++扩展模块代码、Python代理模块、编译系统等等)都是手工完成的,wxWidget的一点点改进都会导致要修改多处wxPython代码,以确保wxPython得到改进或修订。当代码增加上几万行时,这种工作方式变得非常笨拙和琐碎。另一个客观事实是:缺乏一个中心源代码库(那是SourceForge出现之前的时代),因此我们不得不通过电子邮件互相发送代码更新,你可以想象得到这其中的难度。
大约在此时,我不得不“真正”开始主项目的开发了。在我的控制下,一些项目开发者们一起进行设计会晤、设定开发期限,从眼中的灵光一现开始完成一个完整的项目开发。我发现自己又完全回到了C++世界,尽管我可以用Python来进行一些编译及项目的测试脚本。Harri 也无法在上面投入任何时间了,因此wxPython的开发变得比“爬行”还慢了,有时甚至进入了停滞状态。
1997年,我发现了SWIG(简单封装和接口产生器),并意识到它可以帮助我们解决wxPython项目中困扰我们已久的所有维护问题。在三、四周的业余时间里,通过使用SWIG,我几乎将wxPython的全部重新实现了一遍,而在此前用手工完成这项工作耗用了我几周的完整时间以及Harri几个月的部分时间。在转向其他项目一段时间后,我发现wxWidgets 2.0正在积极开发中,而且有了一个全新的架构,因此我不得不重新完成这项工作。但这次,新的架构简化了大量的工作,我仅用了一周的业余时间就完成了!因此,在1998年夏天,第一个“现代版本”的wxPython顺利发布,并从此一直处于活跃开发状态。第一份声明归档与此: [http://groups.yahoo.com/group/python-announce-list/message/95] 正如他们所说的,剩下的部分就是传奇故事了。
必须特别说明的是:SWIG 使得我能够轻松创建和维护成千上百行的代码,因此wxPython的多种功能特性必须感谢David Beazley以及其他项目参与者对SWIG的贡献。通过此书,我们希望能够与您分享对于wxPython的热情,在轻松开发图形用户界面应用程序方面,它是真正的独一无二的开发包。我们写作的初衷是不但为初学者,也为专业人员建造一项有用的资源。
acknowledgments
Our work on this book has been aided by a number of people, in ways both obvious and subtle.
Patrick O’Brien was instrumental in getting this project off the ground and Marjan Bace, our publisher at Manning Publications, gave us the chance to make it happen. Jackie Carter was our first editor at Manning and Lianna Wlasiuk came in at a crucial juncture, and, like a great bullpen pitcher, earned the save. We would like to thank our production team at Manning and every-one who worked behind the scenes on the book, especially our copyeditor Elizabeth Martin and our typesetter Denis Dalinnik. Big thanks also to our agent Laura Lewin for her help and understanding.
We’ve benefited a great deal from the generosity of programmers world-wide in creating the technologies used in this book. First on that list is the crew who developed the wxWidgets foundation of wxPython: Julian Smart, Vadim Zeitlin, Robert Roebling, and the rest of the core wxWidgets team, as well as many contributors. Of course, without Guido van Rossum and other members of the Python language development team, there would be no “Python” in “wxPython.” A large part of this book was written using the jEdit text editor and the images were manipulated using the GIMP.
Thanks also to the many reviewers who looked at the manuscript in its vari-ous stages of development and added their valuable insight along the way. They helped make this a better book: Alex Martelli, Dave Brueck, Christopher Bailey, Mike Stok, Jean Baltus, Thomas Palmer, Jack Herrington, Peter Damoc, Nick Coghlan, Pim Van Heuven, John Paulson, Ian Brown, Stefan Neis, Chris Mellon, Kevin Ollivier, and Doug Tillman. Special thanks to Clint Howarth who was our technical proofreader.
NOEL RAPPIN My wife, Erin, makes my life better every day. Thank you for your strength, your intelligence, and your love. I also want to thank my parents Donna and Donnie and my sister Michelle for supporting me fully and com-pletely. Matt Cohen helped this effort by entertaining me via IM while I was try-ing to write. Finally, I want to thank my daughter Emma, who is now old enough to be excited to see her name in a book, and my son Elliot, in anticipation of the day he will also be glad to see his name.
ROBIN DUNN I’d like to thank my wife, Malaura, and my children, Jordyn, Myka, Samuel, and Christian, for their patience, understanding, and love. You make it worth the effort to get past all the difficulties of life. I’d also like to thank the many wonderful members of the wxPython user community whose praise and excitement have helped me to stay motivated and have helped me to take wxPython from an interesting toy to a very useful tool that thousands of develop-ers all around the world love and depend upon. And finally, many thanks go to Mitch Kapor, John Anderson, David Surovell, and others at the Open Source Applications Foundation for believing in the Open Source concept, the poten-tials of wxPython, and especially for believing in my capabilities and funding my work on wxPython for several years.
about this book
Who should read this book?
Naturally, we’d love everybody to read this book. If you are reading this in the bookstore, trying to decide whether to purchase it, we say, go for it! Buy one for the people next to you too—they’ll thank you later.
That said, we did have certain assumptions about you, the reader, in mind as we wrote this book. We assume that you don’t need us to explain the basics of the Python programming language. We present a lot of Python code in this book. We think Python code is pretty easy to understand, but we want to let you know up front that we don’t have a tutorial on Python basics. If you’d like a Python tutorial, we recommend Manning’s The Quick Python Book, by Daryl Harms and Kenneth McDonald. We also assume that you are at least familiar with the basic terms describing graphical interface objects, and have at least some familiarity with graphical interfaces from a user’s perspective. More advanced user interface concepts, or less familiar user interface display elements, will be described as they come up. We do not assume that you have any prior knowledge of wxPython. If you do have prior experience with wxPython, we expect that you’ll still be able to find new information here, or, at the very least, you’ll find this book to be a more useful resource than the existing online documentation.
How this book is organized
We’ve divided wxPython In Action into three parts. The first part is an introduc-tion to wxPython concepts, a tutorial on how to get started with wxPython, and some information on wxPython best practices. The chapters in part 1 are: Chapter 1, Welcome to wxPython In this chapter, we introduce wxPython, explain to you why it’s the greatest thing since sliced bread, and give some background on the technologies used to create wxPython. Chapter 2, Giving your wxPython program a solid foundation The two most important objects in wxPython are discussed. Every application must have an application object and a top-level window. This chapter will show you how to start a wxPython program, and how to manage its lifecycle. Chapter 3, Working in an event-driven environment Like all GUI toolkits, control in wxPython is managed by events. This chapter discusses how events are handled, and how you can use them as hooks to drive your functionality. Chapter 4, Making wxPython easier to handle with PyCrust PyCrust is a Python shell written in wxPython that contains many advanced and useful features. Not only can you use PyCrust for your wxPython develop-ment, you can wrap your program inside it for debugging purposes, and you can reuse the PyCrust components in your own applications. Chapter 5, Creating your blueprint This chapter discusses best practices in three areas that are often difficult for GUI programmers. We show how to use refactoring to improve the structure and maintainability of your code. The Model/View/Controller design pattern is explored, and we’ll show you how to unit test our GUI code to minimize errors. Chapter 6, Working with the basic building blocks This chapter is a bridge between parts one and two. Building on the basic ideas already shown, we give hints of some of the features discussed in parts 2 and 3 as we build a sketchpad application. Part 2 begins the more detailed portion of the book. The chapters in part 2 take a look at the most commonly used parts of wxPython. This includes a tour of the basic widget set, a look at standard frames and dialogs, and information on drawing and layout. The chapters in part 2 are: ABOUT THIS BOOK Chapter 7, Working with the basic controls This chapter covers the API for the basic widget set, including text fields, but-tons, list boxes, and the like. Chapter 8, Putting widgets in frames All your wxPython widgets will be inside a frame or a dialog. In this chapter we cover how frames work, what kind of frames there are, and how to manage widgets within a frame. Chapter 9, Giving users choices with dialogs Dialogs behave slightly differently than frames. We cover how modal dialog boxes work, as well as the standard predefined wxPython dialogs. We’ll also show you how to use wxPython validators to help mange the data in a dialog. Chapter 10, Creating and using wxPython menus Most windowed applications have a menu. We’ll show you how to add menus to the menu bar, and menu items to a menu. Specialized menus, such as checkboxes, and radio menus will also be covered. We’ll also discuss keyboard shortcuts and some usability guidelines for using menus effectively. Chapter 11, Placing widgets with sizers In wxPython, sizers are used to spare you the drudgery of placing your wid-gets manually. There are several useful sizers that are part of wxPython, and we’ll show you how to use them, and what kind of layout is best suited to each. Chapter 12, Manipulating basic graphical images The most basic purpose of any UI toolkit is to draw lines and shapes to the screen. In wxPython, there is a rich set of drawing tools available for your use. There is also a powerful abstraction called a device context which allows you to draw to a target without caring whether the target is a window, a printer, or a file. Part 3 contains a detailed look at more advanced portions of wxPython. It starts with a description of the three most complex wxPython widgets, and continues with a discussion of various print and display mechanisms, closing out with a tour of useful items that didn’t quite earn their own chapter. The chapters in part 3 are: Chapter 13, Building list controls and managing items The wxPython list control gives you the ability to display lists “explorer-style,” in icon mode, list mode, or multi-column report mode. You can also custom-ize sort behavior, and allow users to edit list entries. Chapter 14, Coordinating the grid control If you want something that looks like a spreadsheet, the wxPython grid control is a full-featured widget that will meet your needs. It allows full control over the display and behavior of the grid, and allows for complete customization. Chapter 15, Climbing the tree control The wxPython tree control allows for compact display of hierarchical data, including, but not limited to a directory tree or class hierarchy. You can also allow the user to edit entries on the fly. Chapter 16, Incorporating HTML into your application Within wxPython, you can use HTML to simplify the display and printing of styled text. The HTML engine inside wxPython can also be customized to fit your special needs. Chapter 17, The wxPython printing framework Printing is managed from a wxPython application through several dedicated print, print data, and print preview objects. In this chapter, we explore how all of them work together. Chapter 18, Using other wxPython functionality In this chapter, we cover some important features that are not quite long enough to justify a chapter on their own, including cut and paste, drag and drop, and multithreading.
How to use this book
How you use this book will depend on your wxPython knowledge. We designed this book to be useful for both experts and novices, but we expect that different parts of the book will have more or less resonance for users at different levels.
- If you are a wxPython beginner, you definitely want to start in part 1. Chap-ters 1–3 will give you a solid grounding in wxPython concepts, and chapter 6 will give you a nice overview of the steps in building a reasonably sized program. Chapter 5 will introduce you to some methods for making your code easy to manage, and chapter 4 will have some tools to help you debug and write wxPy-thon applications. As you start writing your own wxPython programs, you’ll also start using the API discussions in part 2—we tried to organize them by function-ality to make it easy to find useful topics.
If you are already familiar with wxPython, you’ll probably be spending most of your time in parts 2 and 3. However, we recommend you take a spin through part 1 as well. If you aren’t familiar with PyCrust, then chapter 4 will be new to you, and we think you might get something useful out of chapter 5 as well. You’ll find discussion of more complex widgets in part 3, and you’ll also see that the code samples in that section tend to be longer and more integrated than in the other sections. The examples in this book were written against Python version 2.3.x—we don’t think we included any of the new 2.4 language features—and wxPython 2.5.x. The 2.6.x release of wxPython came out too late for coverage in this book; how-ever, it was largely a bug fix release, numbered for compliance with wxWidgets. There is one other point that we need to make before we begin. This book is not intended to be a complete reference to every nook and cranny of wxPython. We expect that it will be a useful reference to the features that you are most likely to need to know about, but it is not 100% feature-complete. In the interests of time and space, we had to choose some elements to focus on and others, well, not to. For instance, there are a number of wxPython features inherited from the C++ wxWidgets toolkit that are replicated in the standard Python library—we chose not to cover those features. Also, if you are working in a Windows operating system whose name includes a date in the 1990s, you’ll probably find that some features don’t work exactly as described in some cases and we didn’t have the space to enumerate all of those exceptions. Finally, there were some features of the core widgets set that we determined were either not often used or that we did not have the space to do justice.
Typographical conventions The following conventions are used throughout the book: ■ Courier typeface is used in all code listings. ■ Italics are used to introduce new terms. ■ Courier Bold is sometimes used to draw your attention to a section of code. ■ Code annotations are used when directing your attention to a particular line of code. Annotations are marked with bullets, such as b. ■ Courier typeface is used in text for code words, wxPython class and method names, or snippets of Python code. Code downloads Source code for all of the examples used in this book is available for download from the publisher’s website at www.manning.com/rappin. Where to get more help Although we tried to be as comprehensive as possible, we couldn’t possibly antic-ipate all the uses and issues you might have using wxPython. The main wxPy-thon website at http://www.wxpython.org has some resources that you might visit for insight into your problem. The official online documentation is at http://www. wxpython.org/docs/api/. A collaborative wiki site is available at http://wiki.wxpy-thon.org/, and there are mailing lists that you can subscribe to at http://www.wxpy-thon.org/maillist.php.
Author Online
Help is also available from the Author Online forum, a private web discussion board run by Manning Publications. You are encouraged to use this forum to make comments about the book, ask technical questions, and receive help from the authors and other readers. Use your browser to navigate to www.man-ning.com/rappin to take advantage of this free service. The forum’s welcome page gives you all the information you need to sign up and get going.
- The Author Online forum is one of the ways Manning remains committed to readers. The authors’ participation in the forum is voluntary and without a specified level of commitment. The forum is a great way to share ideas and learn from each other. The Author Online forum will remain accessible from the publisher’s website as long as the book is in print.
about the title
By combining introductions, overviews, and how-to examples, the In Action books are designed to help learning and remembering. According to research in cognitive science, the things people remember are things they discover during self-motivated exploration.
- Although no one at Manning is a cognitive scientist, we are convinced that for learning to become permanent it must pass through stages of exploration, play, and, interestingly, retelling of what is being learned. People understand and remember new things, which is to say they master them, only after actively exploring them. Humans learn in action. An essential part of an In Action guide is that it is example-driven. It encourages the reader to try things out, to play with new code, and explore new ideas. There is another, more mundane, reason for the title of this book: our readers are busy. They use books to do a job or to solve a problem. They need books that allow them to jump in and jump out easily and learn just what they want just when they want it. They need books that aid them “in action.” The books in this series are designed for such readers.
about the cover illustration
The figure on the cover of wxPython in Action is a “Soldat Japonais,” a Japanese soldier. The illustration is taken from a French travel book, Encyclopedie des Voy-ages by J. G. St. Saveur, published in France in 1796. Travel for pleasure was a relatively new phenomenon at the time and travel guides such as this one were popular, introducing both the tourist as well as the armchair traveler to the inhabitants of other regions of France and abroad.
- The diversity of the drawings in the Encyclopedie des Voyages speaks vividly of the uniqueness and individuality of the world’s towns and provinces just 200 years ago. This was a time when the dress codes of two regions separated by a few dozen miles identified people uniquely as belonging to one or the other. The travel guide brings to life a sense of isolation and distance of that period and of every other historic period except our own hyperkinetic present. Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now often hard to tell the inhabitant of one continent from another. Perhaps, trying to view it optimistically, we have traded a cultural and visual diversity for a more varied personal life. Or a more varied and interesting intellectual and technical life. We at Manning celebrate the inventiveness, the initiative, and the fun of the
computer business with book covers based on the rich diversity of regional life two centuries ago, brought back to life by the pictures from this travel guide.