40,79 €
Geometry Management, Event Handling, and more
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, audio player, drawing application, piano tutor, chat application, screen saver, port scanner, and much 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, asyncio based programming 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.
This book is for a beginner to intermediate-level Pythonists who want to build modern, cross-platform GUI applications with the amazingly powerful Tkinter. Prior knowledge of Tkinter is required.
Bhaskar Chaudhary is a professional programmer and information architect. He has a decade of experience 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.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 462
Veröffentlichungsjahr: 2018
Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editors:Aaron LazarAcquisition Editor: Denim PintoContent Development Editors: Lawrence VeigasTechnical Editor: Adhithya HaridasCopy Editor:Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexers: Pratik ShirodkarGraphics: Jisha ChirayilProduction Coordinator: Deepika Naik
First published: November 2015 Second edition: March 2018
Production reference: 1160318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-746-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.
Bhaskar Chaudhary is a professional programmer and information architect. He has a decade of experience 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.
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.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Tkinter GUI Application Development Blueprints Second Edition
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Meet Tkinter
Technical requirements
Project overview
Getting started
GUI programming – the big picture
The root window – your drawing board
Widgets – the building blocks of GUI programs
Some important widget features
Ways to create widgets
Getting to know the core Tkinter widgets
Adding widgets to a parent window
The Tkinter geometry manager
The pack geometry manager
The grid geometry manager
The place geometry manager
Events and callbacks – adding life to programs
Command binding
Passing arguments to callbacks
Limitations of the command option
Event binding
Event patterns
Binding levels
Handling widget-specific variables
Event unbinding and virtual events
Doing it in style
Specifying styles
Some common root window options
Getting interactive help
Summary
QA section
Further reading
Making a Text Editor
Project overview
Getting started – setting up the editor skeleton
Adding a menu and menu items
Adding menu items
Implementing the View menu
Adding a built-in functionality
Indexing and tagging
Index
Tags
Implementing the Select All feature
Implementing the Find Text feature
Types of Toplevel window
Working with forms and dialogs
Working with message boxes
The icons toolbar and View menu functions
Displaying line numbers
Adding the cursor information bar
Adding themes
Creating a context/pop-up menu
Summary
QA section
Further reading
Programmable Drum Machine
Getting started
Technical requirements
Setting up the GUI in OOP
Finalizing the data structure
Creating broader visual elements
Defining getter and setter methods
The number of units and beats per unit features
Loading drum samples
Playing the drum machine
Initializing pygame
Playing complete patterns
Determining the tempo of a rhythm
Tkinter and threading
Tkinter and thread safety
Support for multiple beat patterns
Saving beat patterns
Working with ttk-themed widgets
Summary
QA section
Further reading
Game of Chess
An overview of the chapter
Module requirements for this chapter
Structuring our program
Modeling the data structure
Convention on naming chess pieces
Convention for naming locations on the chessboard
Creating a Piece class
Displaying chess pieces on the chessboard
Defining rules for the chess pieces
Rules for the king, queen, rooks, and bishops
Rules for the Knight
Rules for a pawn
Movement validation of chess pieces
Tracking all available moves
Finding out the current position of the king
Checking whether the king is in check
Making the game functional
Getting the source and destination position
Collecting a list of the moves that need to be highlighted
Highlighting allowed moves
Pre-move validation
Check whether a move will cause check on the King
Recording a move in the data structure
Keep game statistics
Managing user preferences
Summary
QA section
Further reading
Building an Audio Player
An overview of the chapter
External library requirements
The pyglet module
Pmw Tkinter extension
Program structure and broadview skeleton
Deciding the data structure
Creating the Player class
Adding and removing items from a playlist
Adding a single audio file
Removing the selected files from a playlist
Adding all files from a directory
Emptying the playlist
Playing audio and adding audio controls
Adding the play/stop function
Adding the pause/unpause function
Adding the mute/unmute function
Fast forward/rewind function
Adding the next track/previous track function
Adding the volume change function
Creating a seek bar
One-time updates during audio playback
Managing continuous updates
Looping over tracks
Adding a tooltip
Pmw list of extensions
Widgets
Dialogs
Miscellaneous
Summary
QA section
Further reading
Paint Application
Overview of the application
Creating a tiny framework
Setting up a broad GUI structure
Dealing with mouse events
Adding toolbar buttons
Drawing items on the canvas
Adding a color palette
Adding top bar options for draw methods
Drawing irregular lines and super shapes
Drawing irregular lines
Drawing super shapes
Adding functionality to the remaining buttons
Adding functionality to menu items
Summary
QA section
Further reading
Piano Tutor
Technical requirements
A brief primer on piano terms
Learning about scales
Learning about chords
Building the broad GUI structure
Putting up the skeleton structure
Making the piano keyboard
Putting the keyboard together
Playing audio
Building the scales tutor
Building the chord finder section
Building the chord progression tutor
Building the score maker
A note on window responsiveness
Experimenting with the code
Handling widget resize with <Configure>
Summary
QA section
Further reading
Fun with Canvas
Building a screen saver
Graphing with Tkinter
Polar plots with Tkinter
Gravity simulation
Drawing fractals
Voronoi diagrams
Spring pendulum simulation
Chaos game – building triangles out of randomness
Phyllotaxy
3D graphics with Tkinter
Summary
QA section
Further reading
Multiple Fun Projects
Technical requirements
Building a Snake game
Understanding a race condition
Using synchronization primitives
Using queues
Building the Snake game
The View class
The Food class
The Snake class
Queue handler
Creating a Weather Reporter application
A simple socket demo
Building a port scanner
Building a chat application
Creating a phone book application
Creating a new record
Reading from the database
Updating records
Deleting records
Using asyncio with Tkinter
Interfacing with hardware/serial communication
Hardware
Writing the Arduino sketch
Reading serial data
Summary
QA section
Further reading
Miscellaneous Tips
Tracing Tkinter variables
Widget traversal
Validating user input
Key validation mode demo
Focus-out validation mode demo
Formatting widget data
More on fonts
Finer control over font
Building a font selector
Redirecting the command-line output to Tkinter
The class hierarchy of Tkinter
Tips for program design
The model-first policy versus the code-first policy
Separating the model from the view
Selecting the right data structure
Naming variables and methods
The Single Responsibility Principle
Loose coupling
Handling errors and exceptions
Handling cross-platform differences 
Tips for program optimization
Using filter and map
Optimizing variables
Profiling your program
Other optimization tips
Distributing a Tkinter application
py2exe
py2app
PyInstaller
Other freezing tools
The limitations of Tkinter
A limited number of core widgets
Non-Python objects
No support for printing
No support for newer image formats
Inactive development community
Alternatives to Tkinter
wxPython
PyQt
PySide
PyGTK
Other options
Tkinter in Python 2.x
Summary
QA section
Other Books You May Enjoy
Leave a review - let other readers know what you think
Tkinter GUI Application Development Blueprints, Second Edition 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.
Software developers, scientists, researchers, engineers, students, and programming hobbyists with 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 assumed.
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, Making a Text Editor, develops a text editor using 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 writing multithreaded GUI applications.
Chapter 4, Game of Chess, introduces the 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. In addition, it introduces readers to the power of the Tkinter Canvas widget.
Chapter 5, Building an Audio Player, covers 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, Piano Tutor, demonstrates how to represent the given domain information using JSON and then apply the data thus created to create an interactive application. It also discusses the concept of program responsiveness and how to handle it with Tkinter.
Chapter 8, Fun with Canvas, is dedicated to harnessing the powerful visualization capabilities of Tkinter's canvas widget. It looks at examples from several important mathematical domains to build different kinds of useful and beautiful simulations.
Chapter 9, 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, asynchronous programming, and multithreaded programming.
Chapter 10, 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.
We assume an introductory level familiarity with the basic constructs of Python programming language. We use Python version 3.6 with Tkinter 8.6, and it is recommended to stick to these exact versions to avoid compatibility issues.
The programs discussed in this book have been developed on the Linux Mint platform. However, given the multiplatform abilities of Tkinter, you can easily work on other platforms such as Windows, Mac OS, and other distributions of Linux. The links to download and install other project-specific modules and software are mentioned in the respective chapters.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Tkinter-GUI-Application-Development-Blueprints-Second-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/TkinterGUIApplicationDevelopmentBlueprintsSecondEdition_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Welcome to the exciting world of GUI programming with Tkinter. This chapter aims to get 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 (Tool command language), which is 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, multiplatform 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 a wide variety of areas, ranging from small desktop applications to 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:
It is simple to learn (simpler than any other GUI package for Python)
Relatively little code can produce powerful GUI applications
Layered design ensures that it is easy to grasp
It is portable across all operating systems
It is easily accessible, as it comes pre-installed with the standard Python distribution
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 to introduce you to the various components of GUI programming with Tkinter.
We believe that the concepts that you will develop in this chapter 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:
Understanding the concept of a root window and the main loop
Understanding widgets—the building blocks of programs
Getting acquainted with a list of available widgets
Developing layouts by using different geometry managers
Applying events and callbacks to make a program functional
Styling widgets by using styling options and configuring the root widget
We assume a basic working knowledge of Python. You must know how to write and run basic programs in Python.
We will develop our application on the Linux Mint platform. However, since Tkinter is multiplatform, 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.
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 call these dummy applications because they are neither fully functional nor do they serve any practical purpose other than to show a particular feature of Tkinter.
We will write all our projects using Python Version 3.6.3, which is the latest stable release of Python at the time of writing.
The Python download package and instructions for downloading for different platforms are available at https://www.python.org/downloads/release/python-363/.
The installer binaries for macOS X and the Windows platform are available at the aforementioned link.
If you are following along on Unix, Linux, or BSD, the following procedure will install Python from the source.
First, install tk8.6-dev and python3-tk packages on your computer using your applicable package manager. For instance, on Debian-based systems such as Ubuntu and Mint, run the following two commands from the Terminal:
sudo apt install tk8.6-dev
sudo apt install python3-tk
Download Python 3.6.3 from the preceding link and extract it to any location of your choice. Open a Terminal in the location where you extracted Python and type in the following commands:
./configure make make test sudo make altinstall
This should install Python 3.6.3 on your computer. Now open a command line and enter the following command:
$ python3.6
This will open the Python 3.6 interactive shell. Type in the following command:
>>> import tkinter
This command should execute without any errors. 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.6.3, 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 your IDLE or interactive shell:
>>> import tkinter
>>> tkinter._test()
This should confirm the Tcl/Tk Version as 8.6. We are now ready to build our GUI programs!
The next steps are optional and you may skip them at your discretion. While the preceding steps are sufficient for us to develop our programs, I highly recommend that you use a virtual environment for developing your programs.
Virtual environments provide a secluded environment with no conflicts with system programs, and they can be easily reproduced on any other system.
So now let's set up a virtual environment. First, create a folder where you will keep all projects from this book. Let's call it myTkinterProjects or whatever suits you.
Next, find the location of the Python 3.6 installation on your computer. On my computer, I can find the location of the Python installation by running the following command:
$ which python3.6
Take a note of the location. For me it is /usr/local/bin/python3.6. Now open a Terminal in your myTkinterProjects folder and run the following command:
$ virtualenv -p /location/of /python3.6 myvenv/
This will create a new virtual environment in a folder named myvenv inside your project folder.
Lastly, we need to activate this virtual environment. This is done by running the following command:
$ source myenv/bin/activate
Now if you type the command python, it should pick up Python 3.6.3 from within your virtual environment.
From now onward, every time we have to run a Python script or install a new module, we will first activate the virtual environment using the preceding command and run or install the module within this new virtual environment.
As a GUI programmer, you will generally be responsible for deciding the following three aspects of your program:
Which components should appear on the screen?
This involves choosing the components that make the user interface. Typical components include things such as buttons, entry fields, checkboxes, radio buttons, and scrollbars. In Tkinter, the components that you add to your GUI are called widgets. Widgets (short for window gadgets) are the graphical components that make up your application's frontend.
Where should the components go?
This includes deciding the position and the structural layout of various components. In Tkinter, this is referred to as geometry management.
How do components interact and behave?
This involves adding functionality to each component. Each component or widget does something. For example, a button, when clicked on, does something in response. A scrollbar handles scrolling, and checkboxes and radio buttons enable users to make some choices. In Tkinter, the functionality of various widgets is managed by command binding or event binding using callbacks.
The following diagram shows the three components of GUI programming:
Now you will get to know all the core Tkinter widgets. You have already seen two of them in the previous example—the Label and Button widgets. Now, let's explore all the other core Tkinter widgets.
Tkinter includes 21 core widgets, which are as follows:
Top-level
Label
Button
Canvas
Checkbutton
Entry
Frame
LabelFrame
Listbox
Menu
Menubutton
Message
OptionMenu
PanedWindow
Radiobutton
Scale
Scrollbar
Spinbox
Text
Bitmap
Image
Let's write a program to display all of these widgets in the root window.
You may recall that we used the pack() method to add widgets to the dummy application that we developed in the previous section. The pack() method is an example of geometry management in Tkinter.
The pack() method is not the only way of managing the geometry in your interface. In fact, there are three geometry managers in Tkinter that let you specify the position of widgets inside a top-level or parent window.
The three geometry managers are as follows:
pack
: This is the one that we have used so far. It is simple to use for simpler layouts, but it may get very complex for slightly complex layouts.
grid
: This is the most commonly used geometry manager, and provides a table-like layout of management features for easy layout management.
place
: This is the least popular, but it provides the best control for the absolute positioning of widgets.
Now, let's have a look at some examples of all the three geometry managers in action.
Now that you have learned how to add widgets to a screen and position them where you want, let's turn our attention to the third component of GUI programming.
This addresses the question of how to make widgets functional.
Making widgets functional involves making them responsive to events such as the pressing of buttons, the pressing of keys on a keyboard, and mouse clicks.
