Python GUI Programming with Tkinter: Develop responsive and powerful GUI applications with Tkinter, 2nd Edition
- Length: 631 pages
- Edition: 2
- Language: English
- Publisher: Packt Publishing
- Publication Date: 2021-12-09
- ISBN-10: 1801815925
- ISBN-13: 9781801815925
- Sales Rank: #676847 (See Top 100 Books)
Write feature-rich GUI applications from scratch to meet the demands of evolving user needs
Key Features
- Take advantage of Tkinter’s lightweight, portable, and easy-to-use features
- Transform your business requirements into efficient applications
- Build better-organized code and learn to manage an evolving codebase
Book Description
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. Starting from a set of business requirements for a simple data entry form, you’ll build a full-blown application from the ground up, 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, such as version control and unit testing, separation of concerns through the ubiquitous model-view-controller (MVC) design pattern, and object-oriented programming (OOP) to organize your code and go beyond the default Tkinter widget capabilities.
Throughout, the design choices you make are contextualized in important real-world terms. You’ll gain experience with technologies often used in workplace applications, such as SQL databases, network services, and data visualization libraries. You’ll also package your application for wider distribution and tackle the challenge of maintaining compatibility across multiple platforms.
What you will learn
- Produce well-organized, functional, and responsive GUI applications
- Extend the functionality of existing widgets using classes and OOP
- Plan wisely for the expansion of your app using MVC and version control
- Make sure your app works as intended through widget validation and unit testing
- Use tools and processes to analyze and respond to user requests
- Become familiar with technologies used in workplace applications, including SQL, HTTP, Matplotlib, threading, and CSV
- Use PostgreSQL authentication to ensure data security for your application
Who This Book Is For
This book is for programmers who understand the syntax of Python, but do not yet have the skills, techniques, and knowledge to design and implement a complete software application. A fair grasp of basic Python syntax is required.
Table of Contents
- Introduction to Tkinter
- Designing GUI Applications
- Creating Basic Forms with Tkinter and Ttk Widgets
- Organizing our code with Classes
- Reducing User Error with Validation and Automation
- Planning for the Expansion of Our Application
- Creating Menus with Menu and Tkinter Dialogs
- Navigating Records with Treeview and Notebook
- Improving the Look with Styles and Themes
- Maintaining Cross-Platform Compatibility
- Creating Automated Tests with unittest
- Improving Data Storage with SQL
- Connecting to the Cloud
- Asynchronous Programming with Thread and Queue
- Visualizing Data Using the Canvas Widget
- Packaging with setuptools and cx_Freeze
- Appendix
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
Donate to keep this site alive
How to download source code?
1. Go to: https://github.com/PacktPublishing
2. In the Find a repository… box, search the book title: Python GUI Programming with Tkinter: Develop responsive and powerful GUI applications with Tkinter, 2nd Edition
, sometime you may not get the results, please search the main title.
3. Click the book title in the search results.
3. Click Code to download.
1. Disable the AdBlock plugin. Otherwise, you may not get any links.
2. Solve the CAPTCHA.
3. Click download link.
4. Lead to download server to download.