34,79 €
Tkinter is the built-in GUI package that comes with standard
Python distributions. It is a cross-platform package, which
means you build once and deploy everywhere. It is simple
to use and intuitive in nature, making it suitable for
programmers and non-programmers alike.
This book will help you master the art of GUI programming.
It delivers the bigger picture of GUI programming by building
real-world, productive, and fun applications such as a text
editor, drum machine, game of chess, media player, drawing
application, chat application, screen saver, port scanner,
and many more. In every project, you will build on the skills
acquired in the previous project and gain more expertise.
You will learn to write multithreaded programs, network
programs, database driven programs and more. You will
also get to know the modern best practices involved in
writing GUI apps. With its rich source of sample code, you
can build upon the knowledge gained with this book and
use it in your own projects in the discipline of your choice.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 399
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2015
Production reference: 1241115
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-973-8
www.packtpub.com
Author
Bhaskar Chaudhary
Reviewers
Panagiota Katsikouli
Erik S. Rapert
Raphaël Seban
Commissioning Editor
Amarabha Banerjee
Acquisition Editor
Kirk D'costa
Content Development Editor
Susmita Sabat
Technical Editor
Gaurav Suri
Copy Editor
Vedangi Narvekar
Jonathan Todd
Project Coordinator
Judie Jose
Proofreader
Safis Editing
Indexer
Hemangini Bari
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Bhaskar Chaudhary is a professional programmer and information architect. He has an experience of almost 9 years in consulting, contracting, and educating in the field of software development. He has worked with a large set of programming languages on various platforms over the years.
He is an electronics hobbyist and a musician in his free time.
I would like to thank my parents for everything that I am. Thanks to my wife Sangita, son Chaitanya, sisters Priyanki and Shambhavi, niece Akanksha, nephew Praneet, and friend Souvik for being around. Anurag you are always remembered.
I would also like to thank Erik S. Rapert, Panagiota Katsikouli, and Raphaël Seban for reviewing the book and offering countless suggestions to improve it. The book would not have been half as good without their contributions.
Thanks to Susmita Sabat and Kirk D'Costa for providing suggestions to improve the quality of the book.
Panagiota Katsikouli is a PhD researcher in the School of Informatics, University of Edinburgh, UK. Her work is related to developing techniques for the compact representation of location and signal data recorded in mobile sensing devices, such as smartphones or standalone sensors, in order to design and implement lightweight online and/or distributed algorithms to perform various analysis tasks, such as detecting popular paths and indoor localization, on the data. She has received her undergraduate diploma from the Polytechnic School of Patras, Greece, Department of Computer Engineering and Informatics, and her master's degree of computer technology from the same department. Panagiota, in her free time, enjoys writing Python games using the Tkinter library.
Erik S. Rapert is a pale, slim programmer and a twin who loves Linux and video games. He lives in Dallas with his wife, who is also a software engineer. Erik has a wide range of experience, which includes creating blinking LEDs using Arduino, building small desktop apps using Python and Tkinter, web development with PHP or Ruby, and developing cutting-edge virtual reality using C++. He has used a very broad range of programming languages, but Python is one of his favorites.
Thank you William C. Slater for teaching me how to write software. Thank you Andrew Closson for being a teacher. Thank you Ashley for being you.
Raphaël Seban is a French man who is self-trained in computer science since 1981. He obtained a science degree of mathematics and physics in 1986 and then entered active life directly. A computer geek, he never stopped learning new concepts and is learning even today. He worked for two years with IA's R&D department as a software developer and research assistant. After that, in 2000, he decided to create his own company, RAF'INFO, where he worked until 2008.
Since May 2008, Raphaël has mainly contributed to the open source community by developing free software on GitHub (https://github.com/tarball69) and providing help on technical forums.
His famous free software, tkRAD (https://github.com/tarball69/tkRAD/wiki), still remains one of the leading Tkinter Rapid Application Development libraries in Python's community, providing helpful services such as XML widget GUI building and a powerful event manager.
I would like to thank the Packt Publishing team for trusting my Python/Tkinter expertise, especially Bhaskar Chaudhary, the author, who made an actual effort to give his knowledge an educational purpose; Judie Jose, the project coordinator, for her kindness; and Dinesh Rathe, the reviewer acquisition executive who recruited me.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Tkinter GUI Application Development Blueprints will walk you through the process of developing real-world graphical applications using Python and Tkinter, the built-in GUI module of Python.
This book attempts to highlight the features and capabilities of Tkinter while demonstrating best practices involved in writing GUI programs, irrespective of the library that you choose to build your application with. Here, you will learn how to use Tkinter to develop exciting, fun, and useful GUI applications with Tkinter and Python.
We hope to take you on a fun journey through more than 10 projects from different problem domains. As we develop new applications in each project, the book also builds up a catalog of some commonly used strategies to develop real-world applications.
Chapter 1, Meet Tkinter, begins from scratch, providing an overview of Tkinter and covering details of how to create root windows, add widgets to a root window, handle layout with geometry managers, and work with events.
Chapter 2, Make a Text Editor, develops a text editor in the procedural style of programming. It gives readers their first taste of several features of Tkinter and what it is like to develop a real application.
Chapter 3, Programmable Drum Machine, uses object-oriented programming to develop a drum machine that is capable of playing user-composed rhythms. The application can also save compositions and later edit or replay them. Here, you will learn the techniques of designing a GUI application using a model-first philosophy and how to write multithreaded GUI applications.
Chapter 4, A Game of Chess, introduces key aspects of structuring a GUI application using the model-view-controller (MVC) architecture. It also teaches the art of taking a real-world object (chess) and modeling it in the notations that your program can manipulate. It also introduces readers to the power of the Tkinter Canvas widget.
Chapter 5, Building an Audio Player, introduces the concepts of working with external libraries while showing you how to work with many different Tkinter widgets. Most importantly, it shows how to make your own Tkinter widgets, thereby extending the capabilities of the Tkinter manifold.
Chapter 6, Paint Application, looks at the Tkinter Canvas widget in detail. As you will see, the Canvas widget is truly a highlight of Tkinter. The chapter also introduces the concept of the GUI framework, thereby creating reusable code for all your future programs.
Chapter 7, Multiple Fun Projects, works through a series of small but functional projects, demonstrating problems from different domains such as animation, network programming, socket programming, database programming, making graphs, and multithreaded programming.
Chapter 8, Miscellaneous Tips, discusses some vital aspects of GUI programming that, though not covered in the previous chapters, form a common theme in many GUI programs.
The programs discussed in this book have been developed on the Ubuntu platform. However, given the multiplatform abilities of Tkinter, you can easily work along on other platforms such as Windows, Mac OS, and other distributions of Linux.
For this book, you will require Python version 3.4 with Tkinter 8.6 in most parts of the distribution. The links to download and install other project-specific modules and software are mentioned in the respective chapters.
Software developers, scientists, researchers, engineers, students, and programming hobbyists with a basic familiarity with Python will find this book interesting and informative. A motivated Python newbie with a background in writing programs can fill in the gaps of knowledge with a little outside research.
People familiar with basic programming constructs in other programming languages can also catch up with some brief reading on Python. No GUI programming experience is expected.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/9738OS_ColoredImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Welcome to the exciting world of GUI programming with Tkinter. This chapter aims at getting you acquainted with Tkinter, the built-in graphical user interface (GUI) library for all standard Python distributions.
Tkinter (pronounced tea-kay-inter) is the Python interface to Tk, the GUI toolkit for Tcl/Tk.
Tcl (short for Tool Command Language and pronounced as tickle) is a popular scripting language in the domains of embedded applications, testing, prototyping, and GUI development. On the other hand, Tk is an open source, multi-platform widget toolkit that is used by many different languages to build GUI programs.
The Tkinter interface is implemented as a Python module—Tkinter.py in Python 2.x versions and tkinter/__init__.py in Python 3.x versions. If you look at the source code, Tkinter is just a wrapper around a C extension that uses the Tcl/Tk libraries.
Tkinter is suitable for application to a wide variety of areas, ranging from small desktop applications to use in scientific modeling and research endeavors across various disciplines.
When a person learning Python needs to graduate to GUI programming, Tkinter seems to be the easiest and fastest way to get the work done.
Tkinter is a great tool for the programming of GUI applications in Python.
The features that make Tkinter a great choice for GUI programming include the following:
None of the other Python GUI toolkits have all of these features at the same time.
The purpose of this chapter is to make you comfortable with Tkinter. It aims at introducing you to the various components of GUI programming with Tkinter.
By the end of this chapter, you will have developed several partly-functional dummy applications, such as the one shown in the following screenshot:
We believe that the concepts that you will develop here will enable you to apply and develop GUI applications in your area of interest.
The key aspects that we want you to learn from this chapter include the following:
To work on the projects in this chapter, you must have a working copy of Python 3.4.0 installed on your computer.
The Python download package and instructions for downloading for different platforms are available at https://www.python.org/downloads/release/python-340/.
The installer binaries for Mac OS X and the Windows platform are available at the aforementioned link. Python 3.4 is installed by default on Ubuntu 14.04. Unfortunately, Ubuntu 14.04 does not ship with Tkinter. You have to install it manually. Other Linux users can also install the Python Interpreter (v3.4) package from the official repository or build it directly from the source link provided in the aforementioned link.
We will develop our application on the Ubuntu platform. However, since Tkinter is cross-platform, you can follow along with the instructions in this book on Windows, Mac, or any other Linux distribution, without making any modifications to the code.
After installing Python, open the Python 3.4 interactive shell and type in the following command:
This shell command should be executed without an error.
If there are no error messages, the Tkinter module is installed on your Python distribution. When working with examples from this book, we do not support any Python version except for Python 3.4.0, which comes bundled with Tkinter Tcl/Tk Version 8.6. However, most of the examples should work out-of-the-box on other minor Python 3 versions.
To check whether you have the correct Tkinter version on your Python installation, type the following commands in yourIDLE or interactive shell:
This should make a window pop up. The first line in the window reads This is Tcl/Tk version 8.6. Make sure that it is not 8.5 or any earlier version, as Version 8.6 is a vast improvement over its previous versions.
You are ready to code Tkinter GUI applications if your version test confirms it as Tcl/Tk version 8.6.
Let's get started!
This section describes the different styles of importing Tkinter modules. In the preceding example, we imported Tkinter by using the following command:
This method of importing eases the handling of methods defined in the module. That is to say, you can simply access the methods directly. Generally, it is considered bad practice to import all (*) the methods of a module like we did here. This is so because this style of importing leads to memory flooding, namespace confusion, and difficulty in bug tracking and/or reviewing code. Importing into the global namespace can also lead to an accidental overwriting of methods from other libraries in the global namespace.
There are several ways to import Tkinter in which this overlapping can be avoided, with a common way being the following one:
This style of importing does not pollute the namespace with a list of all the methods defined within Tkinter. However, every method within Tkinter will now have to be called by using the tkinter.some_method format instead of directly calling the method.
Another commonly used import style is as follows:
Here too, you do not pollute the current namespace with all the Tkinter methods. Now, you can access methods such astk.some_method. The tk alias is convenient and easy to type. It is commonly used by many developers to import Tkinter.
As a GUI programmer, you will generally be responsible for deciding the following three aspects of your program:
The following figure shows the three components of GUI programming:
Let's delve deeper into each of these three components in the context of Tkinter.
