35,99 €
Tkinter is widely used to build GUIs in Python due to its simplicity. In this book, you’ll discover Tkinter’s strengths and overcome its challenges as you learn to develop fully featured GUI applications.
Python GUI Programming with Tkinter, Second Edition, will not only provide you with a working knowledge of the Tkinter GUI library, but also a valuable set of skills that will enable you to plan, implement, and maintain larger applications. You’ll build a full-blown data entry application from scratch, learning how to grow and improve your code in response to continually changing user and business needs.
You’ll develop a practical understanding of tools and techniques used to manage this evolving codebase and go beyond the default Tkinter widget capabilities. You’ll implement version control and unit testing, separation of concerns through the MVC design pattern, and object-oriented programming to organize your code more cleanly.
You’ll also gain experience with technologies often used in workplace applications, such as SQL databases, network services, and data visualization libraries. Finally, you’ll package your application for wider distribution and tackle the challenge of maintaining cross-platform compatibility.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 888
Veröffentlichungsjahr: 2021
Python GUI Programming with Tkinter
Second Edition
Design and build functional and user-friendly GUI applications
Alan D. Moore
BIRMINGHAM—MUMBAI
"Python" and the Python Logo are trademarks of the Python Software Foundation.
Python GUI Programming with Tkinter
Second Edition
Copyright © 2021 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.
Producer: Tushar Gupta
Acquisition Editor – Peer Reviews: Suresh Jain
Project Editor: Namrata Katare
Content Development Editor: Lucy Wan
Copy Editor: Safis Editing
Technical Editor: Karan Sonawane
Proofreader: Safis Editing
Indexer: Subalakshmi Govindhan
Presentation Designer: Ganesh Bhadwalkar
First published: May 2018 Second edition: October 2021
Production reference: 2281221
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80181-592-5
www.packt.com
Alan D. Moore has been coding in Python since 2005. He lives in Franklin, Tennessee, where he develops database apps for the local government. His technical interests include Python, JavaScript, Linux, and analog electronics. In his free time, he publishes coding videos on the YouTube channel Alan D Moore Codes, makes music, builds guitar effects, volunteers at his church and scout troop, and helps his wife raise their five children.
Profound thanks to Lucy and Alejandro, without whom this book would be riddled with errors; to Cara and the kids for their support and encouragement; and to the Python and Tcl/Tk communities for providing such great software. God bless you all!
Alejandro Rodas de Paz is a computer engineer from Seville, Spain. He has developed several professional and academic Python projects, from artificial intelligence algorithms to DevOps scripting.
Prior to this publication, Alejandro wrote the Packt titles Python Game Development by Example and Tkinter GUI Application Development Cookbook. He also collaborated as a technical reviewer on the book Tkinter GUI Application Development Hotshot.
I would like to thank and dedicate this work to my sister Belen, whose next year will be the beginning of a long and joyful journey. Wish you all the best on this next chapter of life.
Preface
Who this book is for
What this book covers
To get the most out of this book
Get in touch
Introduction to Tkinter
Introducing Tkinter and Tk
Choosing Tkinter
Installing Tkinter
Installing Python 3.9 on Windows
Installing Python 3 on macOS
Installing Python 3 and Tkinter on Linux
Introducing IDLE
Using the shell mode of IDLE
Using the editor mode of IDLE
IDLE as a Tkinter example
Creating a Tkinter Hello World
An overview of basic Tkinter
Building a GUI with Tkinter widgets
Arranging our widgets with geometry managers
Making the form actually do something
Handling data with Tkinter control variables
Using control variables in a callback function
The importance of control variables
Summary
Designing GUI Applications
Analyzing a problem at ABQ AgriLabs
Assessing the problem
Gathering information about the problem
Interviewing the interested parties
Analyzing what we've found out
Information from the data originators
Information from the users of the application
Information from technical support
Information from the data consumer
Documenting specification requirements
Contents of a simple specification
Writing the ABQ data entry program specification
Designing the application
Deciding on input widgets
Grouping our fields
Laying out the form
Laying out the application
Evaluating technology options
Summary
Creating Basic Forms with Tkinter and Ttk Widgets
The Ttk widget set
The Label widget
The Entry widget
The Spinbox widget
The Checkbutton widget
The Radiobutton widget
The Combobox widget
The Text widget
Text widget indices
The Button widget
The LabelFrame widget
Implementing the application
First steps
Building the data record form
The Record Information section
The Environment Data section
The Plant Data section
Finishing the GUI
Writing the callback functions
The Reset function
The Save callback
Finishing up and testing
Summary
Organizing Our Code with Classes
A primer on Python classes
The advantages of using classes
Classes are an integral part of Python
Classes make relationships between data and functions explicit
Classes help create reusable code
Syntax of class creation
Attributes and methods
Magic attributes and methods
Public, private, and protected members
Inheritance and subclasses
Using classes with Tkinter
Improving Tkinter classes
Creating compound widgets
Building encapsulated components
Subclassing Tk
Rewriting our application using classes
Adding a StringVar to the Text widget
Passing in a variable
Synchronizing the widget to the variable
Synchronizing the variable to the widget
Creating a more advanced LabelInput()
Creating a form class
Creating an application class
Summary
Reducing User Error with Validation and Automation
Validating user input
Strategies to prevent data errors
Validation in Tkinter
The validate argument
The validatecommand argument
The invalidcommand argument
Creating validated widget classes
Creating a Date field
Implementing validated widgets in our GUI
Introducing the power of multiple inheritance
Building a validating mixin class
Building validating input widgets with ValidatedMixin
Requiring data
Creating a Date widget
A better Combobox widget
A range-limited Spinbox widget
Validating Radiobutton widgets
Updating our form with validated widgets
Implementing validation interaction between form widgets
Dynamically updating the Spinbox range
Dynamic disabling of fields
Displaying errors
Preventing form submission on error
Automating input
Date automation
Automating Plot, Lab, Time, and Technician
Summary
Planning for the Expansion of Our Application
Separating concerns
The MVC pattern
What is a model?
What is a view?
What is a controller?
Why complicate our design?
Structuring our application directory
Basic directory structure
The abq_data_entry.py file
The README.rst file
Populating the docs folder
Making a Python package
Splitting our application into multiple files
Creating the models module
Moving the widgets
Moving the views
Removing redundancy in our view logic
Using custom events to remove tight coupling
Creating the application file
Running the application
Using version control software
A super-quick guide to using Git
Initializing and configuring a Git repository
Adding and committing code
Viewing and using our commits
Summary
Creating Menus with Menu and Tkinter Dialogs
Solving problems in our application
Planning solutions to the issues
Implementing Tkinter dialogs
Error dialogs with the Tkinter messagebox
Showing error dialogs in ABQ Data Entry
Using filedialog
Using simpledialog and creating a custom dialog
Creating a Login dialog using simpledialog
Incorporating the LoginDialog in our class
Designing the application menu
The Tkinter Menu widget
Using Checkbutton and Radiobutton items
Implementing the ABQ application menu
Adding a Help menu
Adding a File menu
Adding a settings menu
Finishing the menu
Persisting settings
Building a model for settings persistence
Using the settings model in our application
Summary
Navigating Records with Treeview and Notebook
Implementing read and update in the model
Adding read and update to the CSVModel class
Implementing get_all_records()
Implementing get_record()
Adding update capability to save_record()
The Ttk Treeview
Anatomy of a Treeview
Building a file browser
Creating and configuring a Treeview
Populating a Treeview with data
Sorting Treeview records
Using Treeview virtual events
Implementing a record list with Treeview
Creating the RecordList class
Configuring a Treeview widget
Adding a scrollbar for the Treeview
Populating the Treeview
Adding the record list to the application
Modifying the record form for read and update
Adding a current record property
Adding a label to show what is being edited
Adding a load_record() method
Updating the application layout
The Ttk Notebook widget
Adding a notebook to our application
Adding and updating application callbacks
The _show_recordlist() method
The _populate_recordlist() method
The _new_record() method
The _open_record() method
The _on_save() method
Main menu changes
Testing our program
Summary
Improving the Look with Styles and Themes
Working with images in Tkinter
Tkinter PhotoImage
PhotoImage and variable scope
Using Pillow for extended image support
Adding the company logo to ABQ Data Entry
Dealing with the image path problem
Setting a window icon
Adding icons to buttons and menus
Using BitmapImage
Styling Tkinter widgets
Widget color properties
Using widget properties on the MainMenu
Styling widget content with tags
Styling our record list with tags
Working with fonts in Tkinter
Configuring Tkinter fonts
Configuring fonts with strings and tuples
The font module
Giving users font options in ABQ Data Entry
Styling Ttk widgets
TTk styling breakdown
Exploring a Ttk widget
Using themes
Adding some color to ABQ Data Entry
Adding styles to individual form widgets
Fixing the error colors
Styling input widgets on error
Setting themes
Building a theme selector
Summary
Maintaining Cross-Platform Compatibility
Writing cross-platform Python
Filenames and file paths across platforms
Path separators and drives
Case sensitivity
Symbolic links
Path variables
Inconsistent library and feature support
Python's platform-limited libraries
Checking low-level function compatibility
The dangers of the subprocess module
Text file encodings and formats
Graphical and console modes
Writing code that changes according to the platform
Writing cross-platform Tkinter
Tkinter version differences across platforms
Application menus across platforms
Menu widget capabilities
Menu guidelines and standards
Menus and accelerator keys
Cross-platform fonts
Cross-platform theme support
Window zoomed state
Improving our application's cross-platform compatibility
Storing preferences correctly
Specifying an encoding for our CSV file
Making platform-appropriate menus
Preparing our MainMenu class
Adding accelerators
Building the Windows menu
Building the Linux menu
Building the macOS menu
Creating and using our selector function
Summary
Creating Automated Tests with unittest
Automated testing basics
A simple unit test
The unittest module
Writing a test case
TestCase assertion methods
Fixtures
Using Mock and patch
Running multiple unit tests
Testing Tkinter code
Managing asynchronous code
Simulating user actions
Specifying an event sequence
Managing focus and grab
Getting widget information
Writing tests for our application
Testing the data model
Testing file reading in get_all_records()
Testing file saving in save_record()
More tests on the models
Testing our Application object
Testing our widgets
Unit testing the ValidatedSpinbox widget
Integration testing the ValidatedSpinbox widget
Testing our mixin class
Summary
Improving Data Storage with SQL
PostgreSQL
Installing and configuring PostgreSQL
Configuring PostgreSQL using the GUI utility
Configuring PostgreSQL using the command line
Modeling relational data
Primary keys
Using surrogate primary keys
Normalization
First normal form
Second normal form
Third normal form
More normalization forms
Entity-relationship diagrams
Assigning data types
Creating the ABQ database
Creating our tables
Creating the lookup tables
The lab_checks table
The plot_checks table
Creating a view
Populating the lookup tables
Connecting to PostgreSQL with psycopg2
psycopg2 basics
Parameterized queries
Special cursor classes
Integrating SQL into our application
Creating a new model
Saving data
Getting the current seed sample for the plot
Adjusting the Application class for the SQL backend
Implementing SQL logins
Updating the Application._on_save() method
Removing file-based code
Adjusting the DataRecordForm for SQL data
Reordering fields
Fixing the load_record() method
Improving auto-fill
Updating the RecordList for the SQLModel
We're done!
Summary
Connecting to the Cloud
HTTP using urllib
HTTP transaction fundamentals
HTTP status codes
Basic downloading with urllib.request
Generating POST requests
Downloading weather data to ABQ Data Entry
Creating a weather data model
Parsing the XML weather data
Implementing weather data storage
Adding the GUI elements for weather download
RESTful HTTP using requests
Understanding RESTful web services
The Python requests library
Installing and using requests
Interacting with authenticated sites using Session
The requests.Response object
Implementing a REST backend
The authenticate() method
The upload_file() method
The check_file() method
The get_file() method
Integrating REST upload into the application
Creating a CSV extract
Creating the upload callback
Finishing up
SFTP using paramiko
Setting up SSH services for testing
Installing and using paramiko
Using paramiko
Inspecting our connection
Using SFTP
Implementing an SFTP model
Uploading files
Checking a file's existence
Using SFTPModel in our application
Finishing up
Summary
Asynchronous Programming with Thread and Queue
Tkinter's event queue
Event queue control
The update() methods
The after() methods
Common uses of event queue control
Smoothing out display changes
Mitigating GUI freezes
Running code in the background with threads
The threading module
Tkinter and thread safety
Converting our network functions to threaded execution
Using the threaded uploader
Passing messages using a queue
The Queue object
Using queues to communicate between threads
Adding a communication queue to our threaded uploader
Creating a communications protocol
Sending messages from the uploader
Handling queue messages
Using locks to protect shared resources
Understanding the Lock object
Using a Lock object to prevent concurrent uploads
Threading and the GIL
Summary
Visualizing Data Using the Canvas Widget
Drawing and animation with Tkinter's Canvas
Drawing on the Canvas
Rectangles and squares
Ovals, circles, and arcs
Lines
Polygons
Text
Images
Tkinter widgets
Canvas items and state
Canvas object methods
Scrolling the Canvas
Animating Canvas objects
Setting up the playing field
Setting our players
Animating the racers
Running the game loop and detecting a win condition
Creating simple graphs using Canvas
Creating the model method
Creating the chart view
Updating the application
Advanced graphs using Matplotlib
Data model method
Creating the bubble chart view
Updating the Application class
Summary
Packaging with setuptools and cxFreeze
Creating distributable packages with setuptools
Preparing our package for distribution
Creating a requirements.txt file
Creating a pyproject.toml file
Adding a license file
Making our package executable
Configuring a setup.py script
Basic metadata arguments
Packages and dependencies
Adding extra files
Defining commands
Testing the configuration
Creating and using source distributions
Testing our source distribution
Building a wheel distribution
Creating executables with cx_Freeze
First steps with cx_Freeze
The build_exe options
Including external files
Building executables
Cleaning up the build
Building Windows executables with cx_Freeze
Building a Windows installer file
Building macOS executables with cx_Freeze
Building macOS application bundles
Building macOS .dmg files
Summary
Appendices
A: A Quick Primer on reStructuredText
The reStructuredText markup language
Document structure
Lists
Character styles
Blocks and quotes
Tables
Converting RST to other formats
Other ways to render RST
B: A Quick SQL Tutorial
SQL concepts
Syntax differences from Python
SQL operations and syntax
Defining tables and inserting data
Retrieving data from tables
Updating rows, deleting rows, and more WHERE clauses
Subqueries
Joining tables
Managing transactions
Learning more
Other Books You May Enjoy
Index
Cover
Index
Once you've read Python GUI Programming with Tkinter, Second Edition, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.