36,59 €
Over 90 recipes to help you develop widgets, forms, layouts, charts, and much more using the latest features of Python 3
Key Features
Book Description
Python is a multi-domain, interpreted programming language that is easy to learn and implement. With its wide support for frameworks to develop GUIs, you can build interactive and beautiful GUI-based applications easily using Python. This third edition of Python GUI Programming Cookbook follows a task-based approach to help you create effective GUIs with the smallest amount of code. Every recipe in this book builds upon the last to create an entire, real-life GUI application. These recipes also help you solve problems that you might encounter while developing GUIs. This book mainly focuses on using Python's built-in tkinter GUI framework. You'll learn how to create GUIs in Python using simple programming styles and object-oriented programming (OOP). As you add more widgets and expand your GUI, you will learn how to connect to networks, databases, and graphical libraries that greatly enhance the functionality of your GUI. You'll also learn how to use threading to ensure that your GUI doesn't become unresponsive. Toward the end, you'll learn about the versatile PyQt GUI framework, which comes along with its own visual editor that allows you to design GUIs using drag and drop features. By the end of the book, you'll be an expert in designing Python GUIs and be able to develop a variety of GUI applications with ease.
What you will learn
Who this book is for
If you're a programmer or developer looking to enhance your Python skills by writing powerful GUI applications, this book is for you. Familiarity with the Python programming language is necessary to get the most out of the book.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 397
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 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: Denim PintoContent Development Editor: Pathikrit RoySenior Editor: Afshaan KhanTechnical Editor: Ketan KambleCopy Editor: Safis EditingProject Coordinator:Prajakta NaikProofreader: Safis EditingIndexer:Pratik ShirodkarProduction Designer: Deepika Naik
First published: December 2015 Second edition: May 2017 Third edition: October 2019
Production reference: 1111019
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83882-754-0
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,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
Fully searchable for easy access to vital information
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.
Burkhard Meier has more than 19 years of professional experience working in the software industry as a software tester and developer, specializing in software test automation development, execution, and analysis. He has a very strong background in Python 3 software test automation development, as well as in SQL relational database administration, the development of stored procedures, and debugging code.
His previous jobs include working as a senior test automation engineer and designer for InfoGenesis (now Agilysys), QAD, InTouch Health, and FLIR Systems.
Over the past three years, he has also developed several video courses on Python for Packt, the latest course being Mastering Object-Oriented Programming with Python.
Maurice HT Ling is a research assistant professor at the Perdana University School of Data Sciences. He obtained his BSc (Hons) in molecular and cell biology from the University of Melbourne, Australia, in 2004, and a BSc in computing from the University of Portsmouth, United Kingdom, in 2007, before obtaining his Ph.D. in bioinformatics from the University of Melbourne, Australia, in 2009.
He cofounded Python User Group (Singapore) and is instrumental in inaugurating PyCon Asia-Pacific as one of the three major Python conferences worldwide. In his free time, he likes to read, enjoy a cup of coffee, write in his personal journal, and philosophize on various aspects of life.
Rahul Shendge has a bachelor's degree in computer engineering from the University of Pune and is certified in multiple technologies. He is an open source enthusiast and works as a senior software engineer. He has worked in multiple domains, including finance, healthcare, and education.
He has hands-on experience in the cloud, and in designing trading algorithms with machine learning. He is constantly exploring technical novelties and is open-minded and eager to learn about new technologies. He is passionate about helping clients make valuable business decisions using analytics in their respective areas. His main interests are to work on and explore data analytics solutions.
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 and Credits
Python GUI Programming Cookbook Third Edition
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
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
Download the color images
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
Creating the GUI Form and Adding Widgets
Creating our first Python GUI
Getting ready
How to do it…
How it works…
Preventing the GUI from being resized
Getting ready
How to do it…
How it works…
Adding a label to the GUI form
Getting ready
How to do it…
How it works…
Creating buttons and changing their text attributes
Getting ready
How to do it…
How it works…
Creating textbox widgets
Getting ready
How to do it…
How it works…
Setting the focus to a widget and disabling widgets
Getting ready
How to do it…
How it works…
Creating combobox widgets
Getting ready
How to do it…
How it works…
There's more…
Creating a check button with different initial states
Getting ready
How to do it…
How it works…
Using radio button widgets
Getting ready
How to do it…
How it works…
There's more…
Using scrolled text widgets
Getting ready
How to do it…
How it works…
Adding several widgets in a loop
Getting ready
How to do it…
How it works…
Layout Management
Arraning several labels within a label frame widget
Getting ready
How to do it…
How it works…
See also…
Using padding to add space around widgets
Getting ready
How to do it…
How it works…
Dynamically expanding the GUI using widgets
Getting ready
How to do it…
How it works…
There's more…
Aligning GUI widgets by embedding frames within frames
Getting ready
How to do it…
How it works…
Creating menu bars
Getting ready
How to do it…
How it works…
There's more…
Creating tabbed widgets
Getting ready
How to do it…
How it works…
Using the grid layout manager
Getting ready…
How to do it…
How it works…
Look and Feel Customization
Creating message boxes – information, warning, and error
Getting ready
How to do it…
How it works…
How to create independent message boxes
Getting ready
How to do it…
How it works…
How to create the title of a tkinter window form
Getting ready
How to do it…
How it works…
Changing the icon of the main root window
Getting ready
How to do it…
How it works…
Using a spin box control
Getting ready
How to do it...
How it works…
Applying relief – the sunken and raised appearance of widgets
Getting ready
How to do it…
How it works…
Creating tooltips using Python
Getting ready
How to do it…
How it works…
Adding Progressbar to the GUI
Getting ready
How to do it…
How it works…
How to use the canvas widget
Getting ready
How to do it…
How it works…
Data and Classes
How to use StringVar()
Getting ready
How to do it…
How it works…
How to get data from a widget
Getting ready
How to do it…
How it works…
Using module-level global variables
Getting ready
How to do it…
How it works…
How coding in classes can improve the GUI
Getting ready
How to do it…
How it works…
Writing callback functions
Getting ready
How to do it…
How it works…
Creating reusable GUI components
Getting ready
How to do it…
How it works…
Matplotlib Charts
Installing Matplotlib using pip with the .whl extension
Getting ready
How to do it…
How it works…
Creating our first chart
Getting ready
How to do it…
How it works…
There's more…
Placing labels on charts
Getting ready
How to do it...
How it works…
How to give the chart a legend
Getting ready
How to do it…
How it works…
Scaling charts
Getting ready
How to do it…
How it works…
Adjusting the scale of charts dynamically
Getting ready
How to do it…
How it works…
Threads and Networking
How to create multiple threads
Getting ready
How to do it…
How it works…
Starting a thread
Getting ready
How to do it…
How it works…
Stopping a thread
Getting ready
How to do it…
How it works…
How to use queues
Getting ready
How to do it…
How it works…
Passing queues among different modules
Getting ready
How to do it…
How it works…
Using dialog widgets to copy files to your network
Getting ready
How to do it…
How it works…
Using TCP/IP to communicate via networks
Getting ready
How to do it…
How it works…
Using urlopen to read data from websites
Getting ready
How to do it…
How it works…
Storing Data in Our MySQL Database via Our GUI
Installing and connecting to a MySQL server from Python 
Getting ready
How to do it…
How it works…
Configuring the MySQL database connection
Getting ready
How to do it…
How it works…
Designing the Python GUI database
Getting ready
How to do it…
How it works…
Using the SQL INSERT command
Getting ready
How to do it…
How it works…
Using the SQL UPDATE command
Getting ready
How to do it…
How it works…
Using the SQL DELETE command
Getting ready
How to do it…
How it works…
Storing and retrieving data from our MySQL database
Getting ready
How to do it…
How it works…
Using MySQL Workbench
Getting ready
How to do it…
How it works…
There's more…
Internationalization and Testing
Displaying widget text in different languages
Getting ready
How to do it…
How it works…
Changing the entire GUI language all at once
Getting ready
How to do it…
How it works…
Localizing the GUI
Getting ready
How to do it…
How it works…
Preparing the GUI for internationalization
Getting ready
How to do it…
How it works…
How to design a GUI in an agile fashion
Getting ready
How to do it…
How it works…
Do we need to test the GUI code?
Getting ready
How to do it…
How it works…
Setting debug watches
Getting ready
How to do it…
How it works…
Configuring different debug output levels
Getting ready
How to do it…
How it works…
Creating self-testing code using Python's __main__ section
Getting ready
How to do it…
How it works…
Creating robust GUIs using unit tests
Getting ready
How to do it…
How it works…
How to write unit tests using the Eclipse PyDev IDE
Getting ready
How to do it…
How it works…
Extending Our GUI with the wxPython Library
Installing the wxPython library
Getting ready
How to do it…
How it works…
Creating our GUI in wxPython
Getting ready
How to do it…
How it works…
Quickly adding controls using wxPython
Getting ready
How to do it…
How it works…
Trying to embed a main wxPython app in a main tkinter app
Getting ready
How to do it…
How it works…
Trying to embed our tkinter GUI code into wxPython
Getting ready
How to do it…
How it works…
Using Python to control two different GUI frameworks
Getting ready
How to do it…
How it works…
Communicating between the two connected GUIs
Getting ready
How to do it…
How it works…
Building GUIs with PyQt5
Installing PyQt5
Getting ready
How to do it...
How it works...
Installing the PyQt5 Designer tool
Getting ready
How to do it...
How it works...
Writing our first PyQt5 GUI
Getting ready
How to do it...
How it works...
Changing the title of the GUI
Getting ready
How to do it...
How it works...
There's more...
Refactoring our code into object-oriented programming
Getting ready
How to do it...
How it works...
Inheriting from QMainWindow
Getting ready
How to do it...
How it works...
Adding a status bar widget
Getting ready
How to do it...
How it works...
Adding a menu bar widget
Getting ready
How to do it...
How it works...
Starting the PyQt5 Designer tool
Getting ready
How to do it...
How it works...
Previewing the form within the PyQt5 Designer
Getting ready
How to do it...
How it works...
Saving the PyQt5 Designer form
Getting ready
How to do it...
How it works...
Converting Designer .ui code into .py code
Getting ready
How to do it...
How it works...
Understanding the converted Designer code
Getting ready
How to do it...
How it works...
Building a modular GUI design
Getting ready
How to do it...
How it works...
Adding another menu item to our menu bar
Getting ready
How to do it...
How it works...
There's more...
Connecting functionality to the Exit menu item
Getting ready
How to do it...
How it works...
Adding a Tab Widget via the Designer
Getting ready
How to do it...
How it works...
Using layouts in the Designer
Getting ready
How to do it...
How it works...
Adding buttons and labels in the Designer
Getting ready
How to do it...
How it works...
There's more...
Best Practices
Avoiding spaghetti code
Getting ready
How to do it…
How it works…
Using __init__ to connect modules
Getting ready
How to do it…
How it works…
Mixing fall-down and OOP coding
Getting ready
How to do it…
How it works…
Using a code naming convention
Getting ready
How to do it…
How it works…
There's more...
When not to use OOP
Getting ready
How to do it…
How it works…
How to use design patterns successfully
Getting ready
How to do it…
How it works…
Avoiding complexity
Getting ready
How to do it…
How it works…
GUI design using multiple notebooks
Getting ready
How to do it…
How it works…
Other Books You May Enjoy
Leave a review - let other readers know what you think
In the third edition of this book, we will explore the beautiful world of graphical user interfaces (GUIs) using the Python programming language. We will be using the latest version of Python 3. All of the recipes from the first and second editions are included in this edition, except for the outdated OpenGL library, which is not very Pythonic, after all. We have added an entirely new chapter to the third edition, and we have dramatically changed the style of this third edition to give it more of a cookbook format. By doing so, hopefully, it is easier to apply the recipes to real-world programming situations, providing tested and working solutions.
This is a programming cookbook. Every chapter is self-contained and explains a certain programming solution. We will start very simply, yet throughout the course of this book, we will build a working application written in Python 3. Each recipe will extend the building of this application. Along the way, we will talk about networks, queues, databases, the PyQt5 graphical library, and many more technologies. We will apply design patterns and use best practices.
The book assumes that you have some experience of using the Python programming language, but that is not really required to successfully use this book. This book can also be used as an introduction to the Python programming language, if, and only if, you are dedicated in your desire to become a Pythonic programmer.
If you are an experienced developer in any other language, you will have a fun time extending your professional toolbox by adding the ability to write GUIs using Python to your toolbox.
This book is for programmers who wish to create a GUI. You might be surprised by what we can achieve by creating beautiful, functional, and powerful GUIs using the Python programming language. Python is a wonderful, intuitive programming language, and is very easy to learn.
I invite you to start on this journey now. It will be a lot of fun!
Chapter 1, Creating the GUI Form and Adding Widgets, explains how to develop our first GUI in Python. We will start with the minimum code required to build a running GUI application. Each recipe then adds different widgets to the GUI form.
Chapter 2, Layout Management, explores how to arrange widgets to create our Python GUI. The grid layout manager is one of the most important layout tools built into tkinter that we will be using.
Chapter 3, Look and Feel Customization, offers several examples of how to create a GUI with good look and feel. On a practical level, we will add functionality to the Help | About menu item that we created in one of the recipes.
Chapter 4, Data and Classes, discusses saving the data our GUI displays. We will start using object-oriented programming (OOP) in order to extend Python's built-in functionality.
Chapter 5, Matplotlib Charts, explains how to create beautiful charts that visually represent data. Depending on the format of the data source, we can plot one or several columns of data within the same chart.
Chapter 6, Threads and Networking, explains how to extend the functionality of our Python GUI using threads, queues, and network connections. This will show us that our GUI is not limited at all to the local scope of our PC.
Chapter 7, Storing Data in Our MySQL Database via Our GUI, shows us how to connect to a MySQL database server. The first recipe in this chapter will show you how to install the free MySQL Server Community Edition, while, in the following recipes, we will create databases and tables, and then load data into those tables and modify it. We will also read the data back out from the MySQL server into our GUI.
Chapter 8, Internationalization and Testing, explains how to internationalize our GUI by displaying text on labels, buttons, tabs, and other widgets in different languages. We will start with a simple example and then explore how we can prepare our GUI for internationalization at the design level. We will also explore several ways to automatically test our GUI using Python's built-in unit testing framework.
Chapter 9, Extending Our GUI with the wxPython Library, introduces another Python GUI toolkit that currently does not ship with Python. It is called wxPython, and we will be using the Phoenix version of wxPython, which was designed to work well with Python 3.
Chapter 10, Building GUIs with PyQt5, shows you how to use the wonderful PyQt5 GUI programming framework. Tesla Motors uses this to build their GUI software, and, in this chapter, we will explore the beautiful world of drag and drop IDE GUI development using Python binding with Qt5, which, underneath the hood, is built upon C++. If you wish to get serious about Python GUI development, you need to study this chapter in addition to tkinter.
Chapter 11, Best Practices, explores different best practices that can help us to build our GUI in an efficient way and keep it both maintainable and extendable. Best practices are applicable to any good code, and our GUI is no exception when it comes to designing and implementing good software practices.
To make optimum use of the content in this book, please bear the following points in mind:
All the recipes in this book were developed using Python 3.7 on a Windows 10 64-bit OS. They have not been tested on any other configuration. As Python is a cross-platform language, the code from each recipe is expected to run everywhere.
If you are using a Mac, it does come with built-in Python, yet it might be missing some modules such as
tkinter
, which we will use throughout this book.
We are using Python 3.7, and the creator of Python intentionally chose not to make it backward-compatible with Python 2. If you are using a Mac or Python 2, you might have to install Python 3.7 from
www.python.org
in order to successfully run the recipes in this book.
If you really wish to run the code in this book on Python 2.7, you will have to make some adjustments. For example,
tkinter
in Python 2.x has an uppercase
T
. The Python 2.7 print statement is a function in Python 3.7 and requires parentheses.
While the
End of Life
(
EOL
) for the Python 2.x branch has been extended to the year 2020, I would strongly recommend that you start using Python 3.7 and later.
Why hold on to the past, unless you really have to? Here is a link to the
Python Enhancement Proposal
(
PEP
) 373 that refers to the EOL of Python 2:
https://www.python.org/dev/peps/pep-0373/
.
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.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.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
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-Cookbook-Third-Edition. 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!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838827540_ColorImages.pdf.
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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.packtpub.com/support/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.
In this chapter, we will develop our first GUI in Python. We will start with the minimum code required to build a running GUI application. Each recipe then adds different widgets to the GUI form.
We will start by using the tkinter GUI toolkit.
The old world of the DOS Command Prompt has long been outdated. Some developers still like it for development work. The end user of your program expects a more modern, good-looking GUI.
In this book, you will learn how to develop GUIs using the Python programming language.
In the first two recipes, we will show the entire code, consisting of only a few lines of code. In the following recipes, we will only show the code to be added to the previous recipes because, otherwise, the book would get too long, and seeing the same code over and over again is rather boring.
At the beginning of each chapter, I will show the Python modules that belong to each chapter. I will then reference the different modules that belong to the code shown, studied, and run.
By the end of this chapter, we will have created a working GUI application that consists of labels, buttons, textboxes, comboboxes, check buttons in various states, and radio buttons that change the background color of the GUI.
Here is an overview of the Python modules (ending in a .py extension) for this chapter:
In this chapter, we start creating amazing GUIs using Python 3.7 or later. We will cover the following topics:
Creating our first Python GUI
Preventing the GUI from being resized
Adding a label to the GUI form
Creating buttons and changing their text attributes
Creating textbox widgets
Setting the focus to a widget and disabling widgets
Creating combobox widgets
Creating a check button with different initial states
Using radio button widgets
Using scrolled text widgets
Adding several widgets in a loop
Python is a very powerful programming language. It ships with the built-in tkinter module. In only a few lines of code (four, to be precise) we can build our first Python GUI.
To follow this recipe, a working Python development environment is a prerequisite. The IDLE GUI, which ships with Python, is enough to start. IDLE was built using tkinter!
By default, a GUI created using tkinter can be resized. This is not always ideal. The widgets we place onto our GUI forms might end up being resized in an improper way, so in this recipe, we will learn how to prevent our GUI from being resized by the user of our GUI application.
This recipe extends the previous one, Creating our first Python GUI, so one requirement is to have typed the first recipe yourself into a project of your own. Alternatively, you can download the code from https://github.com/PacktPublishing/Python-GUI-Programming-Cookbook-Third-Edition/.
Here are the steps to prevent the GUI from being resized:
Start with the module from the previous recipe and save it as
Gui_not_resizable.py
.
Use the
Tk
instance variable,
win
, to call the
resizable
method:
win.resizable(False, False)
Here is the code to prevent the GUI from being resized (GUI_not_resizable.py):
Run the code. Running the code creates this GUI:
Let's go behind the scenes to understand the code better.
Line 18 prevents the Python GUI from being resized.
Theresizable()method is of theTk()class and, by passing in(False, False), we prevent the GUI from being resized. We can disable both thexandydimensions of the GUI from being resized, or we can enable one or both dimensions by passing inTrueor any number other than zero.(True, False)would enable thexdimension but prevent the y dimension from being resized.
Running this code will result in a GUI similar to the one we created in the first recipe. However, the user can no longer resize it. Also, note how the maximize button in the toolbar of the window is grayed out.
Why is this important? Because once we add widgets to our form, resizing our GUI can make it not look the way we want it to look. We will add widgets to our GUI in the next recipes, starting with Adding a label to the GUI form.
We also added comments to our code in preparation for the recipes contained in this book.
We've successfully learned how to prevent the GUI from being resized. Now, let's move on to the next recipe.
A label is a very simple widget that adds value to our GUI. It explains the purpose of the other widgets, providing additional information. This can guide the user to the meaning of an Entry widget, and it can also explain the data displayed by widgets without the user having to enter data into it.
We are extending the first recipe,Creating our first Python GUI. We will leave the GUI resizable, so don't use the code from the second recipe (or comment the win.resizable line out).
Perform the following steps to add a label to the GUI from:
Start with the
First_GUI.py
module and save it as
GUI_add_label.py
.
Import
ttk
:
from tkinter import ttk
Use
ttk
to add a label:
ttk.Label(win, text="A Label")
Use the grid layout manager to position the label:
.grid(column=0, row=0)
In order to add a Label widget to our GUI, we will import the ttk module from tkinter. Please note the two import statements on lines 9 and 10.
The following code is added just abovewin.mainloop(), which is located at the bottom of the first and second recipes (GUI_add_label.py):
Let's go behind the scenes to understand the code better.
In line 10 of the preceding code, we import a separate module from the tkinter package. The ttk module has some advanced widgets such as a notebook, progress bar, labels, and buttons that look different. These help to make our GUI look better. In a sense, ttk is an extension within the tkinter package.
We still need to import the tkinter package, but we need to specify that we now want to also use ttk from the tkinter package.
Line 19 adds the label to the GUI, just before we call mainloop.
We pass our window instance into the ttk.Label constructor and set the text attribute. This becomes the text our Label will display. We also make use of the grid layout manager, which we'll explore in much more depth in Chapter 2, Layout Management.
Observe how our GUI suddenly got much smaller than in the previous recipes. The reason why it became so small is that we added a widget to our form. Without a widget, the tkinter package uses a default size. Adding a widget causes optimization, which generally means using as little space as necessary to display the widget(s). If we make the text of the label longer, the GUI will expand automatically. We will cover this automatic form size adjustment in a later recipe in Chapter 2, Layout Management.
Try resizing and maximizing this GUI with a label and watch what happens. We've successfully learned how to add a label to the GUI form.
Now, let's move on to the next recipe.
In this recipe, we will add a button widget, and we will use this button to change an attribute of another widget that is a part of our GUI. This introduces us to callback functions and event handling in a Python GUI environment.
This recipe extends the previous one, Adding a label to the GUI form. You can download the entire code from https://github.com/PacktPublishing/Python-GUI-Programming-Cookbook-Third-Edition/.
In line 19, we assign the label to a variable, a_label, and in line 20, we use this variable to position the label within the form. We need this variable in order to change its attributes in the click_me() function. By default, this is a module-level variable, so as long as we declare the variable above the function that calls it, we can access it inside the function.
Line 23 is the event handler that is invoked once the button gets clicked.
In line 29, we create the button and bind the command to the click_me() function.
Lines 20 and 30 both use the grid layout manager, which will be discussed in Chapter 2, Layout Management, in the Using the grid layout manager recipe. This aligns both the label and the button. We also change the text of the label to include the word red to make it more obvious that the color has been changed. We will continue to add more and more widgets to our GUI, and we will make use of many built-in attributes in the other recipes of this book.
We've successfully learned how to create buttons and change their text attributes. Now, let's move on to the next recipe.
In tkinter, a typical one-line textbox widget is called Entry. In this recipe, we will add such an Entry widget to our GUI. We will make our label more useful by describing what the Entry widget is doing for the user.
This recipe builds upon the Creating buttons and changing their text attributes recipe, so download it from the repository and start working on it.
