Python GUI Programming with Tkinter - Second Edition

Book description

Transform your evolving user requirements into feature-rich Tkinter applications

Key Features

  • Extensively revised with new content on RESTful networking, classes in Tkinter, and the Notebook widget
  • Take advantage of Tkinter's lightweight, portable, and easy-to-use features
  • 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. 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.

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

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. Introduction to Tkinter
    1. Introducing Tkinter and Tk
      1. Choosing Tkinter
      2. Installing Tkinter
        1. Installing Python 3.9 on Windows
        2. Installing Python 3 on macOS
        3. Installing Python 3 and Tkinter on Linux
      3. Introducing IDLE
        1. Using the shell mode of IDLE
        2. Using the editor mode of IDLE
        3. IDLE as a Tkinter example
      4. Creating a Tkinter Hello World
    2. An overview of basic Tkinter
      1. Building a GUI with Tkinter widgets
      2. Arranging our widgets with geometry managers
      3. Making the form actually do something
      4. Handling data with Tkinter control variables
        1. Using control variables in a callback function
        2. The importance of control variables
    3. Summary
  3. Designing GUI Applications
    1. Analyzing a problem at ABQ AgriLabs
      1. Assessing the problem
      2. Gathering information about the problem
        1. Interviewing the interested parties
      3. Analyzing what we've found out
        1. Information from the data originators
        2. Information from the users of the application
        3. Information from technical support
        4. Information from the data consumer
    2. Documenting specification requirements
      1. Contents of a simple specification
      2. Writing the ABQ data entry program specification
    3. Designing the application
      1. Deciding on input widgets
      2. Grouping our fields
      3. Laying out the form
      4. Laying out the application
    4. Evaluating technology options
    5. Summary
  4. Creating Basic Forms with Tkinter and Ttk Widgets
    1. The Ttk widget set
      1. The Label widget
      2. The Entry widget
      3. The Spinbox widget
      4. The Checkbutton widget
      5. The Radiobutton widget
      6. The Combobox widget
      7. The Text widget
        1. Text widget indices
      8. The Button widget
      9. The LabelFrame widget
    2. Implementing the application
      1. First steps
      2. Building the data record form
        1. The Record Information section
        2. The Environment Data section
        3. The Plant Data section
        4. Finishing the GUI
      3. Writing the callback functions
        1. The Reset function
        2. The Save callback
      4. Finishing up and testing
    3. Summary
  5. Organizing Our Code with Classes
    1. A primer on Python classes
      1. The advantages of using classes
        1. Classes are an integral part of Python
        2. Classes make relationships between data and functions explicit
        3. Classes help create reusable code
      2. Syntax of class creation
        1. Attributes and methods
        2. Magic attributes and methods
        3. Public, private, and protected members
      3. Inheritance and subclasses
    2. Using classes with Tkinter
      1. Improving Tkinter classes
      2. Creating compound widgets
      3. Building encapsulated components
        1. Subclassing Tk
    3. Rewriting our application using classes
      1. Adding a StringVar to the Text widget
        1. Passing in a variable
        2. Synchronizing the widget to the variable
        3. Synchronizing the variable to the widget
      2. Creating a more advanced LabelInput()
      3. Creating a form class
      4. Creating an application class
    4. Summary
  6. Reducing User Error with Validation and Automation
    1. Validating user input
      1. Strategies to prevent data errors
      2. Validation in Tkinter
        1. The validate argument
        2. The validatecommand argument
        3. The invalidcommand argument
    2. Creating validated widget classes
      1. Creating a Date field
    3. Implementing validated widgets in our GUI
      1. Introducing the power of multiple inheritance
      2. Building a validating mixin class
      3. Building validating input widgets with ValidatedMixin
        1. Requiring data
        2. Creating a Date widget
        3. A better Combobox widget
        4. A range-limited Spinbox widget
        5. Validating Radiobutton widgets
      4. Updating our form with validated widgets
      5. Implementing validation interaction between form widgets
        1. Dynamically updating the Spinbox range
        2. Dynamic disabling of fields
      6. Displaying errors
      7. Preventing form submission on error
    4. Automating input
      1. Date automation
      2. Automating Plot, Lab, Time, and Technician
    5. Summary
  7. Planning for the Expansion of Our Application
    1. Separating concerns
      1. The MVC pattern
        1. What is a model?
        2. What is a view?
        3. What is a controller?
      2. Why complicate our design?
    2. Structuring our application directory
      1. Basic directory structure
        1. The abq_data_entry.py file
        2. The README.rst file
        3. Populating the docs folder
        4. Making a Python package
    3. Splitting our application into multiple files
      1. Creating the models module
      2. Moving the widgets
      3. Moving the views
        1. Removing redundancy in our view logic
        2. Using custom events to remove tight coupling
      4. Creating the application file
      5. Running the application
    4. Using version control software
      1. A super-quick guide to using Git
        1. Initializing and configuring a Git repository
        2. Adding and committing code
        3. Viewing and using our commits
    5. Summary
  8. Creating Menus with Menu and Tkinter Dialogs
    1. Solving problems in our application
      1. Planning solutions to the issues
    2. Implementing Tkinter dialogs
      1. Error dialogs with the Tkinter messagebox
      2. Showing error dialogs in ABQ Data Entry
      3. Using filedialog
      4. Using simpledialog and creating a custom dialog
        1. Creating a Login dialog using simpledialog
        2. Incorporating the LoginDialog in our class
    3. Designing the application menu
      1. The Tkinter Menu widget
        1. Using Checkbutton and Radiobutton items
      2. Implementing the ABQ application menu
        1. Adding a Help menu
        2. Adding a File menu
        3. Adding a settings menu
        4. Finishing the menu
      3. Persisting settings
        1. Building a model for settings persistence
        2. Using the settings model in our application
    4. Summary
  9. Navigating Records with Treeview and Notebook
    1. Implementing read and update in the model
      1. Adding read and update to the CSVModel class
        1. Implementing get_all_records()
        2. Implementing get_record()
        3. Adding update capability to save_record()
    2. The Ttk Treeview
      1. Anatomy of a Treeview
      2. Building a file browser
        1. Creating and configuring a Treeview
        2. Populating a Treeview with data
        3. Sorting Treeview records
        4. Using Treeview virtual events
    3. Implementing a record list with Treeview
      1. Creating the RecordList class
        1. Configuring a Treeview widget
        2. Adding a scrollbar for the Treeview
        3. Populating the Treeview
    4. Adding the record list to the application
      1. Modifying the record form for read and update
        1. Adding a current record property
        2. Adding a label to show what is being edited
        3. Adding a load_record() method
      2. Updating the application layout
        1. The Ttk Notebook widget
        2. Adding a notebook to our application
      3. Adding and updating application callbacks
        1. The _show_recordlist() method
        2. The _populate_recordlist() method
        3. The _new_record() method
        4. The _open_record() method
        5. The _on_save() method
      4. Main menu changes
      5. Testing our program
    5. Summary
  10. Improving the Look with Styles and Themes
    1. Working with images in Tkinter
      1. Tkinter PhotoImage
        1. PhotoImage and variable scope
      2. Using Pillow for extended image support
      3. Adding the company logo to ABQ Data Entry
        1. Dealing with the image path problem
      4. Setting a window icon
      5. Adding icons to buttons and menus
        1. Using BitmapImage
    2. Styling Tkinter widgets
      1. Widget color properties
        1. Using widget properties on the MainMenu
      2. Styling widget content with tags
        1. Styling our record list with tags
    3. Working with fonts in Tkinter
      1. Configuring Tkinter fonts
        1. Configuring fonts with strings and tuples
        2. The font module
      2. Giving users font options in ABQ Data Entry
    4. Styling Ttk widgets
      1. TTk styling breakdown
        1. Exploring a Ttk widget
        2. Using themes
      2. Adding some color to ABQ Data Entry
        1. Adding styles to individual form widgets
        2. Fixing the error colors
        3. Styling input widgets on error
      3. Setting themes
        1. Building a theme selector
    5. Summary
  11. Maintaining Cross-Platform Compatibility
    1. Writing cross-platform Python
      1. Filenames and file paths across platforms
        1. Path separators and drives
        2. Case sensitivity
        3. Symbolic links
        4. Path variables
      2. Inconsistent library and feature support
        1. Python's platform-limited libraries
        2. Checking low-level function compatibility
        3. The dangers of the subprocess module
      3. Text file encodings and formats
      4. Graphical and console modes
      5. Writing code that changes according to the platform
    2. Writing cross-platform Tkinter
      1. Tkinter version differences across platforms
      2. Application menus across platforms
        1. Menu widget capabilities
        2. Menu guidelines and standards
        3. Menus and accelerator keys
      3. Cross-platform fonts
      4. Cross-platform theme support
      5. Window zoomed state
    3. Improving our application's cross-platform compatibility
      1. Storing preferences correctly
      2. Specifying an encoding for our CSV file
      3. Making platform-appropriate menus
        1. Preparing our MainMenu class
        2. Adding accelerators
        3. Building the Windows menu
        4. Building the Linux menu
        5. Building the macOS menu
        6. Creating and using our selector function
    4. Summary
  12. Creating Automated Tests with unittest
    1. Automated testing basics
      1. A simple unit test
      2. The unittest module
        1. Writing a test case
        2. TestCase assertion methods
        3. Fixtures
        4. Using Mock and patch
        5. Running multiple unit tests
    2. Testing Tkinter code
      1. Managing asynchronous code
      2. Simulating user actions
        1. Specifying an event sequence
      3. Managing focus and grab
      4. Getting widget information
    3. Writing tests for our application
      1. Testing the data model
        1. Testing file reading in get_all_records()
        2. Testing file saving in save_record()
        3. More tests on the models
      2. Testing our Application object
      3. Testing our widgets
        1. Unit testing the ValidatedSpinbox widget
        2. Integration testing the ValidatedSpinbox widget
      4. Testing our mixin class
    4. Summary
  13. Improving Data Storage with SQL
    1. PostgreSQL
      1. Installing and configuring PostgreSQL
        1. Configuring PostgreSQL using the GUI utility
        2. Configuring PostgreSQL using the command line
    2. Modeling relational data
      1. Primary keys
        1. Using surrogate primary keys
      2. Normalization
        1. First normal form
        2. Second normal form
        3. Third normal form
        4. More normalization forms
      3. Entity-relationship diagrams
      4. Assigning data types
    3. Creating the ABQ database
      1. Creating our tables
        1. Creating the lookup tables
        2. The lab_checks table
        3. The plot_checks table
      2. Creating a view
      3. Populating the lookup tables
    4. Connecting to PostgreSQL with psycopg2
      1. psycopg2 basics
      2. Parameterized queries
      3. Special cursor classes
    5. Integrating SQL into our application
      1. Creating a new model
        1. Saving data
        2. Getting the current seed sample for the plot
      2. Adjusting the Application class for the SQL backend
        1. Implementing SQL logins
        2. Updating the Application._on_save() method
        3. Removing file-based code
      3. Adjusting the DataRecordForm for SQL data
        1. Reordering fields
        2. Fixing the load_record() method
        3. Improving auto-fill
      4. Updating the RecordList for the SQLModel
      5. We're done!
    6. Summary
  14. Connecting to the Cloud
    1. HTTP using urllib
      1. HTTP transaction fundamentals
        1. HTTP status codes
      2. Basic downloading with urllib.request
        1. Generating POST requests
      3. Downloading weather data to ABQ Data Entry
        1. Creating a weather data model
        2. Parsing the XML weather data
        3. Implementing weather data storage
      4. Adding the GUI elements for weather download
    2. RESTful HTTP using requests
      1. Understanding RESTful web services
      2. The Python requests library
        1. Installing and using requests
        2. Interacting with authenticated sites using Session
        3. The requests.Response object
      3. Implementing a REST backend
        1. The authenticate() method
        2. The upload_file() method
        3. The check_file() method
        4. The get_file() method
      4. Integrating REST upload into the application
        1. Creating a CSV extract
        2. Creating the upload callback
        3. Finishing up
    3. SFTP using paramiko
      1. Setting up SSH services for testing
      2. Installing and using paramiko
        1. Using paramiko
        2. Inspecting our connection
        3. Using SFTP
      3. Implementing an SFTP model
        1. Uploading files
        2. Checking a file's existence
      4. Using SFTPModel in our application
        1. Finishing up
    4. Summary
  15. Asynchronous Programming with Thread and Queue
    1. Tkinter's event queue
      1. Event queue control
        1. The update() methods
        2. The after() methods
      2. Common uses of event queue control
        1. Smoothing out display changes
        2. Mitigating GUI freezes
    2. Running code in the background with threads
      1. The threading module
        1. Tkinter and thread safety
      2. Converting our network functions to threaded execution
        1. Using the threaded uploader
        2. Passing messages using a queue
        3. The Queue object
        4. Using queues to communicate between threads
      3. Adding a communication queue to our threaded uploader
      4. Creating a communications protocol
      5. Sending messages from the uploader
      6. Handling queue messages
    3. Using locks to protect shared resources
      1. Understanding the Lock object
      2. Using a Lock object to prevent concurrent uploads
        1. Threading and the GIL
    4. Summary
  16. Visualizing Data Using the Canvas Widget
    1. Drawing and animation with Tkinter's Canvas
      1. Drawing on the Canvas
        1. Rectangles and squares
        2. Ovals, circles, and arcs
        3. Lines
        4. Polygons
        5. Text
        6. Images
        7. Tkinter widgets
        8. Canvas items and state
      2. Canvas object methods
      3. Scrolling the Canvas
      4. Animating Canvas objects
        1. Setting up the playing field
        2. Setting our players
        3. Animating the racers
        4. Running the game loop and detecting a win condition
    2. Creating simple graphs using Canvas
      1. Creating the model method
      2. Creating the chart view
      3. Updating the application
    3. Advanced graphs using Matplotlib
      1. Data model method
      2. Creating the bubble chart view
      3. Updating the Application class
    4. Summary
  17. Packaging with setuptools and cxFreeze
    1. Creating distributable packages with setuptools
      1. Preparing our package for distribution
        1. Creating a requirements.txt file
        2. Creating a pyproject.toml file
        3. Adding a license file
        4. Making our package executable
      2. Configuring a setup.py script
        1. Basic metadata arguments
        2. Packages and dependencies
        3. Adding extra files
        4. Defining commands
        5. Testing the configuration
      3. Creating and using source distributions
        1. Testing our source distribution
      4. Building a wheel distribution
    2. Creating executables with cx_Freeze
      1. First steps with cx_Freeze
      2. The build_exe options
      3. Including external files
      4. Building executables
        1. Cleaning up the build
      5. Building Windows executables with cx_Freeze
        1. Building a Windows installer file
      6. Building macOS executables with cx_Freeze
        1. Building macOS application bundles
        2. Building macOS .dmg files
    3. Summary
  18. Appendices
  19. A: A Quick Primer on reStructuredText
    1. The reStructuredText markup language
      1. Document structure
      2. Lists
      3. Character styles
      4. Blocks and quotes
      5. Tables
    2. Converting RST to other formats
      1. Other ways to render RST
  20. B: A Quick SQL Tutorial
    1. SQL concepts
      1. Syntax differences from Python
    2. SQL operations and syntax
      1. Defining tables and inserting data
      2. Retrieving data from tables
      3. Updating rows, deleting rows, and more WHERE clauses
      4. Subqueries
      5. Joining tables
      6. Managing transactions
    3. Learning more
  21. Other Books You May Enjoy
  22. Index

Product information

  • Title: Python GUI Programming with Tkinter - Second Edition
  • Author(s): Alan D. Moore
  • Release date: October 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781801815925