29,99 €
Explore Python’s GUI frameworks and create visually stunning and feature-rich applications
Key FeaturesIntegrate stunning data visualizations using Tkinter Canvas and MatplotlibUnderstand the basics of 2D and 3D animation in GUI applicationsExplore PyQt’s powerful features to easily design and customize your GUI applicationsBook Description
A responsive graphical user interface (GUI) helps you interact with your application, improves user experience, and enhances the efficiency of your applications. With Python, you’ll have access to elaborate GUI frameworks that you can use to build interactive GUIs that stand apart from the rest.
This Learning Path begins by introducing you to Tkinter and PyQt, before guiding you through the application development process. As you expand your GUI by adding more widgets, you'll work with networks, databases, and graphical libraries that enhance its functionality. You'll also learn how to connect to external databases and network resources, test your code, and maximize performance using asynchronous programming. In later chapters, you'll understand how to use the cross-platform features of Tkinter and Qt5 to maintain compatibility across platforms. You’ll be able to mimic the platform-native look and feel, and build executables for deployment across popular computing platforms.
By the end of this Learning Path, you'll have the skills and confidence to design and build high-end GUI applications that can solve real-world problems.
This Learning Path includes content from the following Packt products:
Python GUI Programming with Tkinter by Alan D. MooreQt5 Python GUI Programming Cookbook by B. M. HarwaniWhat you will learnVisualize graphs in real time with Tkinter’s animation capabilitiesUse PostgreSQL authentication to ensure data security for your applicationWrite unit tests to avoid regression when updating codeHandle different signals generated on mouse clicks using QSpinBox and slidersEmploy network concepts, internet browsing, and Google Maps in UIUse graphics rendering to implement animations in your GUIWho this book is for
If you’re an intermediate Python programmer looking to enhance your coding skills by writing powerful GUIs in Python using PyQT and Tkinter, this is an ideal Learning Path for you. A strong understanding of the Python language is a must to grasp the concepts explained in this book.
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 Tkinter. He 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. B. M. Harwani is founder and owner of Microchip Computer Education based in Ajmer, India that provides computer education in all programming and web developing platforms. Being involved in the teaching field for over 20 years, he has developed the art of explaining even the most complicated topics in a straightforward and easily understandable fashion. His latest books published include jQuery Recipes published by Apress, Introduction to Python Programming and Developing GUI Applications with PyQT published by Cengage Learning, The Android Tablet Developer's Cookbook published by Addison-Wesley Professional, UNIX & Shell Programming published by Oxford University Press, Qt5 Python GUI Programming Cookbook published by Packt.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Veröffentlichungsjahr: 2019
Copyright © 2019 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 authors 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.
First Published: June 2019
Production Reference: 1200619
Published by Packt Publishing Ltd. Livery Place, 35 Livery Street Birmingham, B3 2PB, U.K.
ISBN 978-1-83898-847-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry-leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.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.packt.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.
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 Tkinter. He 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.
B. M. Harwani is founder and owner of Microchip Computer Education based in Ajmer, India that provides computer education in all programming and web developing platforms. Being involved in the teaching field for over 20 years, he has developed the art of explaining even the most complicated topics in a straightforward and easily understandable fashion. His latest books published include jQuery Recipes published by Apress, Introduction to Python Programming and Developing GUI Applications with PyQT published by Cengage Learning, The Android Tablet Developer's Cookbook published by Addison-Wesley Professional, UNIX & Shell Programming published by Oxford University Press, Qt5 Python GUI Programming Cookbook published by Packt.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright
Python GUI Programming - A Complete Reference Guide
About Packt
Why Subscribe?
Packt.com
Contributors
About the Authors
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
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
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
Creating a User Interface with Qt Components
Introduction
PyQt
Ways of creating GUI applications
Displaying a welcome message
Understanding the Label widget
Methods
Understanding the Line Edit widget
Methods
Understanding the Push Button widget
How to do it...
How it works...
Using the Radio Button widget
Understanding Radio Button
Methods 
Signal description
How to do it...
How it works...
Grouping radio buttons
Getting ready
How to do it...
How it works...
Displaying options in the form of checkboxes
Getting ready
Method application
Signal description
How to do it...
How it works...
Displaying two groups of checkboxes
Getting ready
How to do it...
How it works...
Event Handling - Signals and Slots
Introduction
Using Signal/Slot Editor
How to do it...
Copying and pasting text from one Line Edit widget to another
Getting ready
How to do it...
How it works...
Converting data types and making a small calculator
How to do it...
How it works...
Using the Spin Box widget
Getting ready
How to do it...
How it works...
Using scrollbars and sliders
Getting ready
How to do it...
How it works...
Using List Widget
Getting ready
How to do it...
How it works...
Selecting multiple list items from one List Widget and displaying them in another
How to do it...
How it works...
Adding items into List Widget
How to do it...
How it works...
Performing operations in List Widget
Getting ready
Methods provided by the QListWidgetItem class
How to do it....
How it works...
Using the Combo Box widget
How to do it…
How it works...
Using the Font Combo Box widget
Getting ready
How to do it…
How it works...
Using the Progress Bar widget
Getting ready
How to do it…
How it works...
Understanding OOP Concepts
Object-oriented programming
Creating a class
Using the built-in class attributes
Accessing class variables in instance methods
Instances
Using classes in GUI
How to do it...
How it works...
Making the application more elaborate
Inheritance
Types of inheritance
Using single inheritance
Getting ready
How to do it...
How it works...
Using multilevel inheritance
Getting ready
How to do it...
How it works...
Using multiple inheritance
Getting ready
How to do it...
How it works...
Understanding Dialogs
Introduction
The input dialog box
Using the input dialog 
How to do it...
How it works...
Using the color dialog
How to do it...
How it works...
Using the font dialog
How to do it...
How it works...
Using the file dialog
Getting ready
How to do it...
How it works...
Understanding Layouts
Understanding layouts
Spacers
Using Horizontal Layout
How to do it...
How it works...
Using Vertical Layout
How to do it...
How it works...
Using Grid Layout
How to do it...
How it works...
Using Form Layout
Getting ready
How to do it...
How it works...
Networking and Managing Large Documents
Introduction
Creating a small browser
How to do it...
How it works...
Creating a server-side application
How to do it...
How it works...
Establishing client-server communication
How to do it...
How it works...
Creating a dockable and floatable sign-in form
Getting ready
How to do it...
How it works...
Multiple Document Interface 
Getting ready
How to do it...
How it works...
Displaying information in sections using Tab Widget
How to do it...
How it works...
Creating a custom menu bar
How to do it…
How it works...
Database Handling
Introduction
Creating the cursor object
Creating a database
How to do it…
How it works…
Creating a database table
How to do it…
How it works…
Inserting rows in the specified database table
How to do it…
How it works…
Displaying rows in the specified database table
How to do it…
How it works…
Navigating through the rows of the specified database table
How to do it…
How it works…
Searching a database table for specific information
How to do it…
How it works…
Creating a signin form – applying an authentication procedure
How to do it…
How it works…
Updating a database table – changing a user's password 
How to do it…
How it works…
Deleting a row from a database table
How to do it…
How it works…
Using Graphics
Introduction
Displaying mouse coordinates
How to do it...
How it works...
Displaying coordinates where the mouse button is clicked and released
How to do it...
How it works...
Displaying a point where the mouse button is clicked
How to do it...
How it works...
Drawing a line between two mouse clicks
How to do it...
How it works...
Drawing lines of different types
How to do it...
How it works...
Drawing a circle of a desired size
How to do it...
How it works...
Drawing a rectangle between two mouse clicks
How to do it...
How it works...
Drawing text in a desired font and size
How to do it...
How it works...
Creating a toolbar that shows different graphics tools
How to do it…
How it works...
Plotting a line using Matplotlib
Getting ready
How to do it...
How it works...
Plotting a bar using Matplotlib
Getting ready
How to do it...
How it works...
Implementing Animation
Introduction
Implementing animation
Displaying a 2D graphical image
How to do it...
How it works...
Making a ball move down on the click of a button
How to do it...
How it works...
Making a bouncing ball
How to do it...
How it works...
Making a ball animate as per the specified curve
How to do it...
How it works...
Using Google Maps
Introduction
Finding out details of a location or a landmark
How to do it…
How it works…
Getting complete information from latitude and longitude values
How to do it…
How it works…
Finding out the distance between two locations
How to do it…
How it works…
Displaying location on Google Maps 
How to do it…
How it works…
Other Books You May Enjoy
Leave a review - let other readers know what you think
A responsive graphical user interface (GUI) helps you interact with your application, improves user experience, and enhances the efficiency of your applications. With Python, you’ll have access to elaborate GUI frameworks that you can use to build interactive GUIs that stand apart from the rest.
This Learning Path begins by introducing you to Tkinter and PyQt, before guiding you through the application development process. As you expand your GUI by adding more widgets, you'll work with networks, databases, and graphical libraries that enhance its functionality. You'll also learn how to connect to external databases and network resources, test your code, and maximize performance using asynchronous programming. In later chapters, you'll understand how to use the cross-platform features of Tkinter and Qt5 to maintain compatibility across platforms. You’ll be able to mimic the platform-native look and feel, and build executables for deployment across popular computing platforms.
By the end of this Learning Path, you'll have the skills and confidence to design and build high-end GUI applications that can solve real-world problems.
This Learning Path includes content from the following Packt products:
Python GUI Programming with Tkinter
by Alan D. Moore
Qt5 Python GUI Programming Cookbook
by B. M. Harwani
If you’re an intermediate Python programmer looking to enhance your coding skills by writing powerful GUIs in Python using PyQT and Tkinter, this is an ideal Learning Path for you. A strong understanding of the Python language is a must to grasp the concepts explained in this book.
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, Creating Automated Tests with unittest, discusses how to verify your code with automated unit tests and integration tests.
Chapter 10, 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 11,Connecting to the Cloud, covers how to work with cloud services such as web services and FTP to download and upload data.
Chapter 12, Visualizing Data Using the Canvas Widget, teaches you how to work with the Tkinter Canvas widget to create visualizations and animations.
Chapter 13,Creating a User Interface with Qt Components, teaches you to use certain basic widgets of Qt Designer and how to display a welcome message along with the username. You will learn how to choose one out of several options using radio buttons and choose more than one out of several options by making use of checkboxes.
Chapter 14, Event Handling – Signals and Slots, covers how to execute specific tasks on the occurrence of certain events on any widget, as well as how to copy and paste text from one Line Edit widget to another, convert data types and make a small calculator, and use spin boxes, scrollbars, and sliders. You will also learn to perform multiple tasks using the List Widget.
Chapter 15, Understanding OOP Concepts, discusses object-oriented programming concepts such as how to use classes, single inheritance, multilevel inheritance in GUI applications, and multiple inheritance.
Chapter 16, Understanding Dialogs, explores the use of certain dialogs, where each dialog is meant for fetching a different kind of information. You will also learn to take input from the user using input dialog.
Chapter 17, Understanding Layouts, explains how to arrange widgets horizontally, vertically, and in different layouts by making use of Horizontal Layout, Vertical Layout, Grid Layout, as well as how to arrange widgets in two column layout using Form Layout.
Chapter 18, Networking and Managing Large Documents, demonstrates how to make a small browser, establish a connection between client and server, create a dockable and floatable sign in form, and manage more than one document using MDI. Also, you will learn how to display information in sections using the Tab widget, and how to create a custom menu bar that invokes different graphics tools when a specific menu item is chosen.
Chapter 19, Database Handling, outlines how to manage a SQLite database to keep information for future use. Using the knowledge gained, you will learn to make a signin form that checks whether a user's email address and password are correct or not.
Chapter 20,Using Graphics, explains how to display certain graphics in the application. You will also learn how to create a toolbar of your own that contains certain tools that can be used to draw different graphics.
Chapter 21,Implementing Animation, features how to display a 2D graphical image, make a ball move down on the click of a button, make a bouncing ball, and make a ball animate as per the specified curve.
Chapter 22,Using Google Maps, showcases how to use the Google API to display location and other information. You will learn to derive the distance between two locations and display location on Google Maps on the basis of longitude and latitude values that are entered.
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 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.
To run Python scripts on Android devices, you need to install QPython on your Android device. To package Python scripts into Android’s APK using the Kivy library, you need to install Kivy, a Virtual Box, and Buildozer packager. Similarly, to run Python scripts on iOS devices, you need a macOS machine and some library tools, including Cython.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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-A-Complete-Reference-Guide. 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!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.