Tkinter GUI Application Development Cookbook Tkinter GUI Application Development Cookbook A practical solution to your GUI development problems with Python and Tkinter Alejandro Rodas de Paz BIRMINGHAM MUMBAI Tkinter GUI Application Development Cookbook 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 b.
Trang 2
A practical solution to your GUI development problems withPython and Tkinter
Trang 4Development Cookbook
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.
Trang 5not have been possible without their love and support.
Trang 6Mapt is an online digital library that gives you full access to over5,000 books and videos, as well as industry leading tools to helpyou plan your personal development and advance your career Formore information, please visit our website.
Trang 7Spend less time learning and more time coding with
practical eBooks and Videos from over 4,000 industryprofessionals
Improve your learning with Skill Plans built especially foryou
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Trang 8Did you know that Packt offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade tothe 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 service@packtpub.com 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 exclusivediscounts and offers on Packt books and eBooks
Trang 9Contributors
Trang 10Alejandro Rodas de Paz is a computer engineer from Seville,
Spain He has developed several projects with Python, from webcrawlers to artificial intelligence algorithms He has also used
Trang 11Javier Becerra Elcinto received his PhD in image processing
from the Université de Bordeaux in 2006 In 2010 he started
working as a self-employed developer working with Python andC++, and in 2014 he cofounded Panoimagen S.L There, he hascontinued to develop software for industrial and precision
agriculture applications Javier lectures regularly on scientific
programming in private companies and several Spanish researchinstitutions
Trang 13Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit auth ors.packtpub.com and apply today We have worked with thousands ofdevelopers and tech professionals, just like you, to help them sharetheir 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
Trang 14As one of the more versatile programming languages, Python is wellknown for its batteries-included philosophy, which includes a richset of modules in its standard library; Tkinter is the library used tobuild desktop applications Built over the Tk GUI toolkit, Tkinter is
a common choice for rapid GUI development, and complex
applications can benefit from the full capabilities of this library.This book covers all of your Tkinter and Python GUI developmentproblems and solutions
Tkinter GUI Application Development Cookbook starts with an
overview of Tkinter classes and at the same time provides recipesfor basic topics, such as layout patterns and event handling Next,this book covers how to develop common GUI patterns, such asentering and saving data, navigating through menus and dialogs,and performing long-running actions in the background You canthen make your apps leverage network resources effectively andperform graphical operations on a canvas and related tasks such asdetecting collisions between items Finally, this book covers usingthemed widgets, an extension of Tk widgets that have a more nativelook and feel
By the end of the book, you will have an in-depth knowledge of
Tkinter classes and know how to use them to build efficient and richGUI applications
Trang 15This book targets Python developers who are familiar with thebasics of the language—syntax, data structures, and OOP—wants tolearn effective solutions to the common challenges of GUI
development, and desires to discover interesting capabilities thatTkinter can offer to build complex applications
You do not need previous experience with Tkinter or other GUIdevelopment libraries since the first part of the book will teach thebasics of the library through the introductory use cases
Trang 16Chapter 1, Getting Started with Tkinter, introduces the structure of a
Tkinter program and shows you how to perform the most commontasks, such as creating widgets and handling user events
Chapter 7, Canvas and Graphics, explores the Canvas widget and the
types of items you can add to the canvas and how to manipulatethem
Chapter 8, Themed Widgets, teaches you how to extend Tkinter
applications with the Tk-themed widget set
Trang 17To get the most out of this book
To get up and running, users will need to have the followingtechnologies installed:
Python 3.x
Any operating system
Trang 18files
You can download the example code files for this book from youraccount at www.packtpub.com If you purchased this book elsewhere, youcan visit www.packtpub.com/support and register to have the files emaileddirectly to you
Once the file is downloaded, please make sure that you unzip orextract 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://githu b.com/PacktPublishing/Tkinter-GUI-Application-Development-Cookbook In case
there's an update to the code, it will be updated on the existing
GitHub repository
Trang 19We also have other code bundles from our rich catalog of books andvideos available at https://github.com/PacktPublishing/ Check them out!
Trang 20We also provide a PDF file that has color images of the
screenshots/diagrams used in this book You can download it here: https://www.packtpub.com/sites/default/files/downloads/TkinterGUIApplicationDevelop mentCookbook_ColorImages.pdf
Trang 21There are a number of text conventions used throughout this book
CodeInText: Indicates code words in text, database table names, foldernames, filenames, file extensions, pathnames, dummy URLs, userinput, and Twitter handles Here is an example:
"The delete() method takes two arguments that indicate the range ofthe characters that should be deleted."
Trang 22Warnings or important notes appear like this Tips and tricks appear like this.
Trang 23Feedback from our readers is always welcome
General feedback: Email feedback@packtpub.com and mention the booktitle in the subject of your message If you have questions about anyaspect of this book, please email us at questions@packtpub.com
Errata: Although we have taken every care to ensure the accuracy
of our content, mistakes do happen If you have found a mistake inthis book, we would be grateful if you would report this to us Pleasevisit www.packtpub.com/submit-errata, selecting your book, clicking on theErrata 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 uswith the location address or website name Please contact us at
copyright@packtpub.com 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 eitherwriting or contributing to a book, please visit authors.packtpub.com
Trang 24Please leave a review Once you have read and used this book, whynot leave a review on the site that you purchased it from? Potentialreaders can then see and use your unbiased opinion to make
purchase decisions, we at Packt can understand what you thinkabout our products, and our authors can see your feedback on theirbook Thank you!
For more information about Packt, please visit packtpub.com
Trang 26Thanks to its clear syntax and the wide ecosystem of libraries andtools, Python has become a popular and general-purpose
programming language From web development to Natural
Language Processing (NLP), you can easily find an open source
library that fits the need of your application domain, and in the lastinstance, you can always use any of the modules included in thePython standard library
The standard library follows the "batteries-included" philosophy,which means that it contains a large collection of utilities: regularexpressions, mathematical functions, networking, and so on The
standard Graphical User Interface (GUI) package of this library
is Tkinter, a thin object-oriented layer on top of Tcl/Tk.
Starting from Python 3, the Tkinter module was renamed to tkinter
(with a lowercase t) It also affects to the tkinter.ttk and tkinter.tix
extensions We will dive into the tkinter.ttk module in the last
chapter of this book, since the tkinter.tix module is officially
deprecated
In this chapter, we will explore several patterns for some basic
classes of the tkinter module and some methods that are common toall widget subclasses
Trang 27application
One of the main advantages of making applications with Tkinter isthat it is very easy to set up a basic GUI with a script of a few lines
As the programs get more complex, it becomes more difficult toseparate logically each part, so an organized structure will help us tokeep our code clean
Trang 28expected However, all our variables are defined in the global
namespace, and the more widgets you add, the more difficult itbecomes to reason about the parts where they are used
Trang 29Wildcard imports ( from import * ) are strongly discouraged in production code because they pollute your global namespace—we only used them here to illustrate an anti-pattern that can be commonly seen in online examples.
These maintainability issues can be addressed with basic OOPtechniques, which are considered good practice in all types ofPython programs
Trang 30To improve the modularity of our simple program, we will define aclass that wraps our global variables:
Trang 31We will follow this convention through all the code samples, so youcan take this template as the starting point of any larger application.
Trang 32We subclassed the Tk class in our example, but it is also common tosubclass other widget classes We did this to reproduce the samestatements that we had before we refactored the code
However, it may be more convenient to subclass Frame or Toplevel inlarger programs, such as those with multiple windows This is
because a Tkinter application should have only one Tk instance, andthe system creates one automatically if you instantiate a widgetbefore you create the Tk instance
Keep in mind that this decision does not affect the structure of our
App class since all widget classes have a mainloop method that
internally starts the Tk main loop
Trang 33Button widgets represent a clickable item of your GUI applications.They typically use a text or an image indicating the action that will
be performed when clicked Tkinter allows you to easily configurethis functionality with some standard options of the Button widgetclass
Trang 34The following contains a button with an image that gets disabledwhen clicked and a list of buttons with the different types ofavailable reliefs:
After executing the preceding code, you will get the followingoutput:
Trang 36The most basic way of instantiation of Button is using the text option
to set the button label and the command option that references thefunction to be invoked when the button is clicked
In out example, we also added PhotoImage via the image option, which
takes precedence over the text string The compound option serves tocombine image and text in the same button, determining the
position where the image is placed It accepts the following
constants as valid values: CENTER, BOTTOM, LEFT, RIGHT, and TOP
The second row of buttons is created with a list comprehension,using the list of RELIEF values The label of each button corresponds
to the name of the constant, so you can note the difference in theappearance of each button
Trang 37We used an attribute to keep a reference to our PhotoImage instance,even though we are not using it outside our init method Thereason is that images are cleared when they are garbage collected,which will happen if we declare it as a local variable and the methodexists
To avoid this, always remember to keep a reference to each PhotoImage
object as long as the window where it is shown is still alive
Trang 38The Entry widget represents a text input displayed in a single line.Along with the Label and Button classes, it is one of the most
commonly used Tkinter classes
Trang 41The Entry widgets are instantiated using the parent window orframe as the first argument and a set of optional keyword
arguments to configure additional options We did not specify anyoptions for the entry corresponding to the username field To keep thepassword secret, we specify the show argument with the string "*",which will display each typed character as an asterisk
With the get() method, we will retrieve the current text as a string.This is used in the print_login method to show the entries' content inthe standard output
The delete() method takes two arguments that indicate the range ofthe characters that should be deleted Keep in mind that the indicesstart at the position 0, and they do not include the character at theend of the range If only one argument is passed, it deletes the
character at that position
In the clear_form() method, we delete from index 0 to the constant END,which means that the whole content is removed Finally, we set thefocus to the username entry
Trang 42The content of an Entry widget can be modified programmaticallywith the insert() method, which takes two arguments:
index: The position to insert the text; note that entry positionsare 0-indexed
string: The text to insert
A common pattern to reset the content of an entry with a defaultvalue can be achieved with a combination of delete() and insert():
entry.delete(0, tk.END)
entry.insert(0, "default value")
Another pattern is to append the text in the current position of thetext cursor Here, you can use the INSERT constant instead of having
Trang 43The Tracing text changes recipe The Validating a text entry recipe
Trang 44Tk variables allow your applications to get notified when an inputchanges its value There are four variable classes in Tkinter: BooleanVar,
DoubleVar, IntVar, and StringVar Each one wraps the value of the
corresponding Python type, which should match the type of theinput widget attached to the variable
This feature is particularly useful if you want to automatically
update certain parts of your application based on the current state
of some input widgets