Python GUI Programming with Tkinter - Alan D Moore - E-Book

Python GUI Programming with Tkinter E-Book

Alan D Moore

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Find out how to create visually stunning and feature-rich applications by empowering Python's built-in Tkinter GUI toolkit

Key Features

  • Explore Tkinter's powerful features to easily design and customize your GUI application
  • Learn the basics of 2D and 3D animation in GUI applications.
  • Learn to integrate stunning Data Visualizations using Tkinter Canvas and Matplotlib.

Book Description

Tkinter is a lightweight, portable, and easy-to-use graphical toolkit available in the Python Standard Library, widely used to build Python GUIs due to its simplicity and availability. This book teaches you to design and build graphical user interfaces that are functional, appealing, and user-friendly using the powerful combination of Python and Tkinter.

After being introduced to Tkinter, you will be guided step-by-step through the application development process. Over the course of the book, your application will evolve from a simple data-entry form to a complex data management and visualization tool while maintaining a clean and robust design. In addition to building the GUI, you'll learn how to connect to external databases and network resources, test your code to avoid errors, and maximize performance using asynchronous programming. You'll make the most of Tkinter's cross-platform availability by learning how to maintain compatibility, mimic platform-native look and feel, and build executables for deployment across popular computing platforms.

By the end of this book, you will have the skills and confidence to design and build powerful high-end GUI applications to solve real-world problems.

What you will learn

  • Implement the tools provided by Tkinter to design beautiful GUIs
  • Discover cross-platform development through minor customizations in your existing application
  • Visualize graphs in real time as data comes in using Tkinter's animation capabilities
  • Use PostgreSQL authentication to ensure data security for your application
  • Write unit tests to avoid regressions when updating code

Who this book is for

This book will appeal to developers and programmers who would like to build GUI-based applications. Knowledge of Python is a prerequisite.

Alan D. Moore is a data analyst and software developer who has been solving problems with Python since 2006. He's developed both open source and private code using frameworks like Django, Flask, Qt, and, of course, Tkinter, and contributes to various open source Python and Javascript projects. Alan maintains a blog by the name alandmoore, where he writes mainly about Python, Linux, free software, and his home studio recordings. Alan lives in Franklin, Tennessee, where he works for the county government, and with his wife, Cara, raises a crew of children who are just as geeky as their dad.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 524

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Python GUI Programming with Tkinter

 

 

 

 

 

 

 

 

Develop responsive and powerful GUI applications with Tkinter

 

 

 

 

 

 

 

Alan D. Moore 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Python GUI Programming with Tkinter

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 Editor: Richa TripathiAcquisition Editor: Alok DhuriContent Development Editor: Priyanka SawantTechnical Editor: Vibhuti GawdeCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Mariammal ChettiyarGraphics: Jason Monteiro Production Coordinator: Shantanu Zagade

First published: May 2018

Production reference: 1110518

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-588-6

www.packtpub.com

 

To my children, may you never be afraid to try, even when you don't have all the answers.
mapt.io

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.

Why subscribe?

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

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.

Contributors

About the author

Alan D. Moore is a data analyst and software developer who has been solving problems with Python since 2006. He's developed both open source and private code using frameworks like Django, Flask, Qt, and, of course, Tkinter, and contributes to various open source Python and Javascript projects.

Alan maintains a blog by the name alandmoore, where he writes mainly about Python, Linux, free software, and his home studio recordings.

Alan lives in Franklin, Tennessee, where he works for the county government, and with his wife, Cara, raises a crew of children who are just as geeky as their dad.

Thanks to my wife, Cara, for her support; Caspian, for listening to me ramble about Python; Mark Soper, Tom Potter, Gayle Moore, and Albert Moore for the wise advice; David Andrews for his expertise; Alok Dhuri, Priyanka Sawant, Vibhuti Gawde, and the Packt team for their hard work and patience; and all the helpful people in the Python and Tkinter communities.

About the reviewer

David Andrews is CTO at a small but growing healthcare technology startup. He has spent many years as a consultant developer in several different industries including sports, finance, publishing, and insurance. His expertise lies in process automation and identifying technological solutions to core business inefficiencies.

David operates his own consultancy group, Andrews Innovations, in Nashville, TN, primarily specializing in bringing startup ideas to fruition for small businesses, including custom development of mobile applications, websites, and SaaS offerings.

I would like to thank Alan particularly for involving me in this process. It has been a true honor. I would also like to thank the good people involved in the publishing process for their patience and guidance as we worked through this.

 

 

 

 

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Python GUI Programming with Tkinter

Dedication

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

Conventions used

Get in touch

Reviews

Introduction to Tkinter

Introducing Tkinter and Tk

Choosing Tkinter

Installing Tkinter

Installing Python 3 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

Creating a better Hello World Tkinter

Summary

Designing GUI Applications with Tkinter

A problem at ABQ AgriLabs

Assessing the problem

Gathering information about the problem

What you found out

Information about the data being collected

Information about the users of the application

Documenting specification requirements

Contents of a simple specification

Writing the ABQ data entry program specification

Designing the application

Exploring Tkinter input widgets

Grouping our fields

Laying out the form

Laying out the application

Summary

Creating Basic Forms with Tkinter and ttk Widgets

Evaluating our technology choices

Choosing a technology

Exploring Tkinter widgets

The Entry widget

The Spinbox widget

The Combobox widget

The Checkbutton widget

The Text widget

The Button widget

The LabelFrame widget

Implementing the application

Saving some time with a LabelInput class

Building the form

Adding LabelFrame and other widgets

Retrieving data from our form

Resetting our form

Building our application class

Saving to CSV

Finishing and testing

Summary

Reducing User Error with Validation and Automation

Validating user input

Strategies to prevent data errors

Validation in Tkinter

Creating a DateEntry widget

Implementing validated widgets in our form

Exploiting the power of multiple inheritance

A validating mixin class

Building our widgets

Requiring data

A Date widget

A better Combobox widget

A range-limited Spinbox widget

Dynamically adjusting the Spinbox range

Updating our form

Displaying errors

Preventing form submission on error

Automating input

Inserting a date

Automating 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

ReStructuredText

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

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

Deciding how to address these problems

Implementing simple Tkinter dialogs

Tkinter messagebox

Showing the error dialogs

Designing our menu 

Creating menus in Tkinter

Implementing our application menu

Showing an About dialog

Adding the menu functionality in the controller

Handling file selection

Making our settings work

Persisting settings

Building a model for settings persistence

Using the settings model in our application

Summary

Navigating Records with Treeview

Implementing read and update in the model

Adding read and update to our model

Implementing  get_all_records()

Implementing  get_record()

Adding update to save_record()

Implementing a record list view

The ttk Treeview

Implementing our record list with Treeview

Configuring a Treeview widget

Adding a scrollbar

Populating the Treeview

Responding to record selection

Modifying the record form for read and update

Updating __init__()

Adding a load_record() method

Updating the rest of the application

Main menu changes

Connecting the pieces in Application

Adding the RecordList view

Moving the model

Populating the record list

Adding the new callbacks

Cleaning up

Testing our program

Summary

Improving the Look with Styles and Themes

Working with images in Tkinter

Tkinter PhotoImage

Adding the company logo

Setting our Window icon

Styling Tkinter widgets

Widget color properties

Using widget properties on our form

Using tags

Styling our record list with tags

Tkinter fonts

Giving users font options

Styling Ttk widgets

Exploring a Ttk widget

Styling our form labels

Styling input widgets on error

Making our Spinbox a Ttk widget

Updating ValidatedMixin

Setting themes

Building a theme selector

Summary

Maintaining Cross-Platform Compatibility

Writing cross-platform Python

Filenames and filepaths across platforms

Path separators and drives

Path separator translation

The os.path module

The pathlib module

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

Windows user experience interaction guidelines

Apple's human interface guidelines

Linux and BSD human interface guidelines

Accelerator keys

Fonts

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

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 our model

Testing file reading in get_all_records()

Testing file saving in save_record()

More tests

Testing our application

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

Connecting with psycopg2

SQL and relational database basics

Basic SQL operations

Syntax differences from Python

Defining tables and inserting data

Retrieving data from tables

Updating rows, deleting rows, and more WHERE clauses

Subqueries

Joining tables

Learning more

Modeling relational data

Normalization

The 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

Integrating SQL into our application

Creating a new model

Adjusting the Application class for the SQL backend

Building a login window

Using the login window

Fixing some model incompatibilities

DataRecordForm creation

Fixing the open_record() method

Fixing the on_save() method

Creating new callbacks

Updating our views for the SQL backend

The data record form

The record list

Last changes

Summary

Connecting to the Cloud

HTTP using urllib

Basic downloading with urllib.request

Creating a download function

Parsing XML weather data

Implementing weather data storage

Creating the SQL table

Implementing the SQLModel.add_weather_data() method

Updating the SettingsModel class

Adding the GUI elements for weather download

HTTP using requests

Installing and using requests

The requests.session() fucntion

The response objects

Implementing API upload

Creating a test HTTP service

Creating our network function

Updating application

Updating the models.py file

Finishing up

FTP using ftplib

Basic concepts of FTP

Creating a test FTP service

Implementing the FTP upload function

Listing files

Retrieving files

Deleting or renaming files

Adding FTP upload to the GUI

Summary

Asynchronous Programming with Thread and Queue

Tkinter's event queue

The after() and after_idle() methods

The update() and update_idletasks () methods

Eliminating freezes with after() and update_idletasks ()

Running code in the background with threading

The threading module

Converting our network functions to threads

Simulating a slow server

Demonstrating the threaded versus non-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

Summary

Visualizing Data Using the Canvas Widget

Drawing and animation with Tkinter's Canvas

Animating Canvas objects

Creating our objects

Animating the racers

Detecting and handling a win condition

Creating simple graphs on the canvas

Creating the model method

Creating the graph view

Updating the application

Advanced graphs using Matplotlib and Tkinter

Data model method

Creating the bubble chart view

Application method

Summary

Packaging with setuptools and cx_Freeze

Using setuptools

Configuring a setup.py script

Basic metadata arguments

Packages and dependencies

Adding extra files

Defining commands

Creating and using source distributions

Testing our source distribution

Building a wheel distribution

Using 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

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Becoming a programmer is not just about learning programming languages; it takes more than a mastery of syntax rules to build applications that enable users to perform work, manage data, or enjoy a game. As programmers, we also need to be able to convert user requests and expectations into designs and pick the best technologies to implement them. We need to be able to organize large code bases, test them, and maintain them in a way that keeps them manageable and free from careless errors.

This book not only teaches you how to use the Tkinter GUI toolkit and a few other libraries; it will also teach you many of the skills you need to move from a writer of short scripts to a writer of medium-sized graphical applications. By the time you've finished the book, you should feel confident that you can develop a simple but useful data-oriented application.

Who this book is for

This book is for beginners who have learned the basics of Python but haven't written much beyond simple scripts or REPL sessions. We'll walk you step-by-step through designing and creating a larger application, and we'll introduce you to skills that will help you advance as a programmer.

It's also aimed at those who have used Python for data science, web development, or system administration, but who now want to branch out into creating GUI applications. We'll go through the knowledge and skills required to create local GUI applications.

Finally, this book may also be useful for experienced Python programmers who just want to learn Tkinter, as most of the book details the finer points of using Tkinter classes.

What this book covers

Chapter 1, Introduction to Tkinter, introduces you to the basics of the Tkinter library and walks you through creating a Hello World application. It will also introduce you to IDLE as an example of a Tkinter application.

Chapter 2, Designing GUI Applications with Tkinter, goes through the process of turning a set of user requirements into a design that we can implement.

 Chapter 3, Creating Basic Forms with Tkinter and ttk Widgets, shows you how to create a basic data entry form that appends data to a CSV file.

Chapter 4, Reducing User Error with Validation and Automation, demonstrates how to automatically populate and validate data in our form's inputs.

Chapter 5, Planning for the Expansion of Our Application, familiarizes you with how to break a small script into multiple files and build a Python module that you can import. It also contains some general advice on how to manage a larger code base.

Chapter 6, Creating Menus with Menu and Tkinter Dialogs, outlines the creation of a main menu using Tkinter. It will also show the use of several built-in dialog types to implement common menu functionality.

Chapter 7, Navigating Records with Treeview, details the construction of a records navigation system using the Tkinter Treeview and the conversion of our application from append-only to full read, write, and update capabilities.

Chapter 8, Improving the Look with Styles and Themes, informs you of how to change the colors, fonts, and widget styles of your application, and how to use them to make your application more usable.

Chapter 9, Maintaining Cross-Platform Compatibility, goes over Python and Tkinter techniques to keep your application running smoothly across Windows, macOS, and Linux systems.

Chapter 10,Creating Automated Tests with unittest, discusses how to verify your code with automated unit tests and integration tests.

Chapter 11,Improving Data Storage with SQL, takes you through the conversion of our application from the CSV flat-files to SQL data storage. You'll learn all about SQL and relational data models as well.

Chapter 12,Connecting to the Cloud, covers how to work with cloud services such as web services and FTP to download and upload data.

Chapter 13,Asynchronous Programming with Thread and Queue, explains how to use asynchronous and multithreaded programming to keep our application responsive during long-running processes.

Chapter 14,Visualizing Data Using theCanvas Widget, teaches you how to work with the Tkinter Canvas widget to create visualizations and animations.

Chapter 15,Packaging with setuptools and cx_Freeze, explores preparing your Python application for distribution as a Python package or a standalone executable.

To get the most out of this book

This book expects that you know the basics of Python 3. You should know how to write and run simple scripts using built-in types and functions, how to define your own functions and classes, and how to import modules from the standard library.

You can follow this book if you run Windows, macOS, Linux, or even BSD. Ensure that you have Python 3 and Tcl/Tk installed (Chapter 1, Introduction to Tkinter, contains instructions for Windows, macOS, and Linux) and that you have an editing environment with which you are comfortable (we suggest IDLE since it comes with Python and uses Tkinter). In the later chapters, you'll need access to the internet so that you can install Python packages and the PostgreSQL database.

Download the example code files

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 at https://github.com/PacktPublishing/Python-GUI-Programming-with-Tkinter. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Get in touch

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.

Reviews

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.

Introduction to Tkinter

Welcome, Python coder! If you've learned the basics of Python and want to start designing powerful GUI applications, this book is for you.

By now, you have no doubt experienced the power and simplicity of Python. Perhaps you've written web services, performed data analysis, or administered servers. Perhaps you've written a game, automated routine tasks, or simply played around with code. But now you're ready to tackle the GUI.

With so much emphasis on web, mobile, and server-side programming, the development of simple desktop GUI applications seems increasingly like a lost art; many otherwise experienced developers have never learned to create one. What a tragedy! Desktop computers still play a vital role in work and home computing, and the ability to build simple, functional applications for this ubiquitous platform should be a part of every software developer's toolbox. Fortunately, for Python coders, that ability is well within reach thanks to Tkinter.

In this chapter, you will cover the following topics:

Discovering Tkinter—a fast, fun, and easy-to-learn GUI library built right into the Python standard library

Learning about IDLE—an editor and development environment written in Tkinter and bundled with Python

Creating two

Hello World

applications to learn the basics of writing a Tkinter GUI

Introducing Tkinter and Tk

The Tk widget library originates from the Tool Command Language (Tcl) programming language. Tcl and Tk were created by John Ousterman while he was a professor at Berkeley in the late 1980s as an easier way to program engineering tools being used at the university. Because of its speed and relative simplicity, Tcl/Tk rapidly grew in popularity among academic, engineering, and Unix programmers. Much like Python itself, Tcl/Tk originated on the Unix platform and only later migrated to macOS and Windows. Tk's practical intent and Unix roots still inform its design today, and its simplicity compared to other toolkits is still a major strength.

Tkinter is a Python interface to the Tk GUI library and has been a part of the Python standard library since 1994 with the release of Python version 1.1, making it the de facto GUI library for Python. Documentation for Tkinter, along with links for further study, can be found in the standard library documentation at https://docs.python.org/3/library/tkinter.html.

Choosing Tkinter

Python coders who want to build a GUI have several toolkit options to choose from; unfortunately, Tkinter is often maligned or ignored as a legacy option. To be fair, it's not a glamorous technology that you can describe in trendy buzzwords and glowing hype. However, Tkinter is not only adequate for a wide variety of applications, it also has the following advantages that can't be ignored:

It's in the standard library

: With few exceptions, Tkinter is available wherever Python is available. There is no need to install

pip

, create virtual environments, compile binaries, or search the web for installation packages. For simple projects that need to be done quickly, this is a clear advantage.

It's stable

: While Tkinter development has not stopped, it is slow and evolutionary. The API has been stable for years, the changes mainly being additional functionality and bug fixes. Your Tkinter code will likely run unaltered for years or decades to come.

It's only a GUI toolkit

: Unlike some other GUI libraries, Tkinter doesn't have its own threading library, network stack, or filesystem API. It relies on regular Python libraries for such things, so it's perfect for applying a GUI to existing Python code.

It's simple and no-nonsense

: Tkinter is straightforward, old-school object-oriented GUI design. To use Tkinter, you don't have to learn hundreds of widget classes, a markup or templating language, a new programming paradigm, client-server technologies, or a different programming language.

Tkinter is not perfect, of course. It also has the following disadvantages:

Look and feel

: It's often derided for its look and feel, which still bear a few artifacts from the 1990s Unix world. This has improved a great deal in the last few years, thanks to updates in Tk itself and the addition of themed widget libraries. We'll learn how to fix or avoid some of Tkinter's more archaic defaults throughout the book.

Complex widgets

: It also lacks more complex widgets, like rich text or HTML rendering widgets. As we'll see later in this book, Tkinter gives us the ability to create complex widgets by customizing and combining its simple ones.

Tkinter might be the wrong choice for a game UI or slick commercial application; however, for data-driven applications, simple utilities, configuration dialogs, and other business logic applications, Tkinter offers all that is needed and more.

Installing Tkinter

Tkinter is included in the Python standard library for the Windows and macOS distributions. That means that, if you have Python on these platforms, you don't need to do anything to install Tkinter.

However, we're going to be exclusively focused on Python 3.x for this book; so, you need to make sure that this is the version you've got installed.

Installing Python 3 on Windows

You can obtain Python 3 installers for Windows from the python.org website by performing the following steps:

Go to

http://www.python.org/downloads/windows

Select the latest Python 3 release. At the time of writing, the latest version is 3.6.4, with 3.7 promising to be out by publishing time.

 

Under the

Files

section, select the Windows executable installer appropriate to your system's architecture (x86 for 32-bit Windows, x86_64 for 64-bit Windows).

Launch the downloaded installer.

Click on

Customize installation

. Make sure the

tcl/tk and IDLE

 option is checked (it should be by default).

Continue through the installer with all defaults.

Installing Python 3 on macOS

As of this writing, macOS ships with Python 2 and Tcl/Tk 8.5 built in. However, Python 2 is scheduled to be deprecated in 2020, and the code in this book will not work with it, so macOS users will need to install Python 3 to follow this book. 

Let's perform the following steps to install Python3 on macOS:

Go to

http://www.python.org/downloads/mac-osx/

Select the latest Python 3 release. At the time of writing, the latest version is 3.6.4, but 3.7 should be out by publication time.

Under the

Files

section, select and download

macOS 64-bit/32-bit installer

.

Launch the

.pkg

file that you've downloaded and follow the steps of the install wizard, selecting defaults.

There is currently no recommended way to upgrade to Tcl/Tk 8.6 on macOS, though it can be done with third-party tools if you wish. Most of our code will work with 8.5, though special mention is made when something is 8.6 only.

Installing Python 3 and Tkinter on Linux

Most Linux distributions include both Python 2 and Python 3, however, Tkinter is not always bundled with it or installed by default.

To find out if Tkinter is installed, open a Terminal and try the following command:

python3 -m tkinter

This should open a simple window showing some information about Tkinter. If you get ModuleNotFoundError instead, you will need to use your package manager to install your distribution's Tkinter package for Python 3. In most major distributions, including Debian, Ubuntu, Fedora, and openSUSE, this package is called python3-tk.

Introducing IDLE

IDLE is an integrated development environment that is bundled with the Windows and macOS Python distributions (it's readily available in most Linux distributions as well, usually as IDLE or IDLE3). IDLE is written in Python using Tkinter, and it provides us with not only an editing environment for Python, but also a great example of Tkinter in action. So, while IDLE's rudimentary feature set may not be considered professional grade by many Python coders, and while you may already have a preferred environment for writing Python code, I encourage you to spend some time using IDLE as you go through this book.

Let's get familiar with IDLE's two primary modes: shell mode and editor mode.

Using the shell mode of IDLE

When you launch IDLE, you begin in shell mode, which is simply a Python Read-Evaluate-Print-Loop (REPL) similar to what you get when you type python in a terminal window.

Take a look at the shell mode in the following screenshot:

IDLE's shell has some nice features that you don't get from the command-line REPL, like syntax highlighting and tab-completion. The REPL is essential to the Python development process, as it gives you the ability to test code in real time and inspect classes and APIs without having to write complete scripts. We'll use the shell mode in later chapters to explore the features and behaviors of modules. If you don't have a shell window open, you can open one by clicking on Start, then selecting Run, and searching for Python shell.

Using the editor mode of IDLE

Editor mode is for creating Python script files, which you can later run. When the book tells you to create a new file, this is the mode you'll use. To open a new file in the editor mode, simply navigate to File|New File in the menu or hit Ctrl + N on the keyboard. 

The following is a window where you can start typing a script:

You can run your script without leaving IDLE by hitting F5 in the editor mode; the output will show up in a shell window.

IDLE as a Tkinter example

Before we start coding with Tkinter, let's take a quick look at what you can do with it by inspecting some of IDLE's UI. Navigate to Options|Configure IDLE from the main menu to open IDLE's configuration settings, where you can change IDLE's fonts, colors and theme, keyboard shortcuts, and default behaviors, as shown in the following screenshot:

Consider some of the following components that make up this user interface:

There are drop-down lists and radio buttons that allow you to select between different options

There are many push buttons that you can click on to execute actions

There is a text window that can display multi-colored text

There are labeled frames that contain groups of components

Each of these components is known as a widget; we're going to meet these widgets and more throughout this book and learn how to use them as they've been used here. We'll begin, however, with something much simpler.

Summary

Now that you've installed Python 3, learned to use IDLE, gotten a taste of the simplicity and power of Tkinter, and have seen how to begin structuring it for more complicated applications, it's time to start writing a real application.

In the next chapter, you'll start your new job at ABQ AgriLabs and be presented with a problem that will need to be solved with your programming skills and Tkinter. You will learn how to dissect this problem, develop a program specification, and design a user-friendly application that will be part of the solution.

Designing GUI Applications with Tkinter

Software applications are developed in three repeating phases: understanding a problem, designing a solution, and implementing the solution. These phases repeat throughout the life of an application, refining and honing it until it is either optimal or obsolete.

In this chapter, we'll learn about the following topics:

Introducing and analyzing a scenario in the workplace that will need a software solution

Documenting the requirements of the solution

Developing a design for a piece of software that implements the solution

A problem at ABQ AgriLabs

Congratulations! Your Python skills have landed you a great data analyst job at ABQ AgriLabs. So far, your job is fairly simple: collating and doing simple data analysis on the CSV files sent to you daily from the lab's data entry staff.

There is a problem, though. You've noted with frustration that the quality of the CSV files from the lab is sadly inconsistent. Data is missing, typos abound, and often the files have to be re-entered in a time-consuming process. The lab director has noticed this as well and, knowing that you are a skilled Python programmer, she thinks you might be able to help.

You've been enlisted to program a solution that will allow the data entry staff to enter lab data into a CSV file with fewer mistakes. Your application needs to be simple and allow as little room for error as possible.

Assessing the problem

Spreadsheets are often a first stop for computer users who need to keep track of data. Their table-like layouts and computational features seem to make them ideal for the task. However, as a set of data grows and is added to by multiple users, the shortcomings of spreadsheets become apparent: they don't enforce data integrity, their table-like layout can be visually confusing when dealing with long rows of sparse or ambiguous data, and users can easily delete or overwrite data if they aren't being careful.

To improve this situation, you propose to implement a simple GUI data entry form that appends data to a CSV file in the format we need. Forms can help to improve data integrity in the several ways:

Allowing only the correct type of data to be entered (for example, only allowing numerals in a number field)

Limiting choices to only valid options

Auto-filling information like current dates, times, and so on

Verifying that entered data is within expected ranges or matches expected patterns

Ensuring that all data has been filled in

By implementing such a form, we can greatly reduce the number of errors being entered by the data entry staff.

Gathering information about the problem

To build the data entry form application, you need to gather details about what it needs to accomplish. Fortunately, you already know the output part of the equation: you need a CSV file containing data about the plants growing in the plots of each laboratory and the environmental conditions at each plot. You work with these files every day, so you're pretty familiar with the field layout.

However, you don't know everything about the data or the process of entering it; you'll need to talk to the other staff involved to find out more information.

First, you'll need to find out more detail about the data being recorded. This isn't always as easy as it sounds. Software needs absolute, black-and-white rules when dealing with data; people, on the other hand, tend to think in generalities about their data, and they often don't consider the exact details of limits or edge cases without some prompting.

As a programmer, it's your job to come up with questions that will bring out the information you need.

You decide you should start with the lab technicians and learn more about the data they're collecting. You come up with the following questions:

What values are acceptable for each field? Are any fields constrained to a set of values?

What units are represented by each of the numeric fields?

Are numeric fields truly number-only fields? Would they ever need letters or symbols?

What range of numbers is acceptable for each numeric field?

How do you record data and how long does it take?

Data isn't the only consideration. If we're making a program to help reduce user error, we also have to understand those users and how they work. In the case of this application, our users will be the data entry staff. We need to ask them questions about their needs and workflow to understand how to create an application that works well for them.

We come up with the following list of questions:

In what format do you get the data you're entering?

When is the data received and how soon is it entered? What's the latest it might be entered?

Are there fields that could be automatically populated? Should users be able to override the auto values?

What's the overall technical ability of the users?

What do you like about the current solution? What do you dislike?

Do users have visual or manual impairments that should be accommodated?

Finally, we need to understand the technology involved with operating our application—the computers, networks, servers, and platforms being used to accomplish the task.

You decide to add the following questions, which you'll assess yourself when you meet with the data entry staff:

What kind of computer does data entry use?

What platform does it run?

How fast or powerful is it?

Is Python available on these systems?

Which Python libraries are available?

What you found out

You start by writing down the following basics about ABQ that you know:

Your ABQ facility has five greenhouses, each operating with a different climate, marked A, B, C, D, and E

Each greenhouse has 20 plots (labeled 1 through 20)

There are currently four seed samples, each coded with a six-character label

Each plot has 20 seeds of a given sample planted in it, as well as its own environmental sensor unit

Information about the data being collected

Your talk with the lab technicians revealed a lot about the data. Four times a day, at 8:00, 12:00, 16:00, and 20:00, each technician checks the plots in one or two labs. They use a paper form to record values at each plot, recording all values to two decimal places. This usually takes 30 to 40 minutes per lab, and the whole process typically takes 90 minutes. 

Each plot has an environmental sensor that detects the light, temperature, and humidity at the plot. Unfortunately, these devices are prone to failure, indicated by an EquipmentFault light on the unit. Technicians record if this light is lit, since it invalidates the environmental data.

Finally, the technicians tell you about the units and acceptable ranges for the fields, which you record in the following chart:

Field
Data type
Notes

Date

Date

The data collection date. Almost always the current date

Time

Time

The start of the period during which measurements were taken. One of 8:00, 12:00, 16:00, or 20:00

Lab

Character

The lab ID, which will be A to E

Technician

Text

The name of the technician recording data

Plot

Int

The plot ID, which will be 1 through 20

Seed Sample

Text

ID string for seed sample. Always a six-character code containing digits 0 to 9 and capital letters A to Z

Fault

Boolean

True if environmental equipment registered a failure, otherwise false

Humidity

Decimal

Absolute humidity in g/m³, roughly between 0.5 and 52.0

Light

Decimal

Amount of sunlight at the plot center in kilolux, between 0 and 100

Temperature

Decimal

Degrees C, should not go below 4 or above 40

Blossoms

Int

The number of blossoms in the plot must be 0 or more, but unlikely to ever approach 1,000

Fruit

Int

The number of fruits in the plot must be 0 or more, but unlikely to ever approach 1,000

Plants

Int

The number of growing plants, between 0 and 20.

Max height

Decimal

The height of the tallest plant in cm. At least 0, unlikely to approach 1,000.

Median height

Decimal

The median height of plants in the plot, in cm. At least 0, unlikely to approach 1,000

Min height

Decimal

The height of the smallest plant in cm. At least 0, unlikely to approach 1,000

Notes

Long Text