Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Tkinter GUI Programming by Example
Tkinter GUI Programming by Example

Tkinter GUI Programming by Example: Learn to create modern GUIs using Tkinter by building real-world projects in Python

eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Tkinter GUI Programming by Example

Meet Tkinter

Hello, and welcome to Tkinter GUI Programming by Example. In this book, we will be building three real-world desktop applications using Python and Tkinter. You will gain the knowledge to fully utilize Tkinter's vast array of widgets to create and lay out any application you choose.

So why use Tkinter? Tkinter comes bundled with Python most of the time, meaning there's no arduous installation process. It's also licensed under a free software license, meaning, unlike some other GUI frameworks, there's no complicated licensing model to battle against when you want to release your software to the outside world.

Tkinter is also very quick and easy to learn. Code can be written both procedurally or using object-oriented practices (which is the preferred style for anything non-experimental), and runs perfectly on any operating system supporting Python development, including Windows, macOS, and Linux.

In this first chapter, we will cover the following topics:

  • Ensuring Tkinter is installed and available
  • Creating a main window in which to display your application
  • Laying out widgets inside the window via geometry managers
  • Creating widgets and displaying them inside your main window
  • Displaying static information via a label widget
  • Creating interactivity with the Button widget
  • Tying widgets to Python functions
  • Using Tkinter's special variables
  • Displaying pop-up messages easily
  • Getting information from the user

Installation

Most of the time, you will not need to install Tkinter as long as you have Python installed. To check, open an instance of the interactive interpreter and type import tkinter (Python 3) or import Tkinter (Python 2). If you don't see an error, then Tkinter is already installed and you are ready to go! Some flavors of Linux will not come with Tkinter by default, and if you receive an error message while performing the previous step, search your distribution's package manager. On Debian-based distributions such as Ubuntu, the package should be called python3-tk. On RPM-based distributions, including Fedora, you may instead find a package called python3-tkinter.

Examples in this book will be written using Python 3.6.1 and Tkinter 8.6. I recommend you also use these versions, or as close to them as possible, when following along. To check your Tkinter version, open an interactive Python prompt and type the following:

>>> import tkinter
>>> tkinter.TkVersion

Once you've got Tkinter installed and ready, we can move on to a brief overview of how we will be structuring a Tkinter application and then dive in and write our first program.

How will the code be structured?

Tkinter exposes many classes. These are known as widgets. A widget is typically any part of the application that needs to be drawn onto the screen, including the main window.

A Tkinter application always needs to have a main window. This is what will be drawn on the screen for the user to see. This is crucial for any GUI application, so much so that if you do not define one, Tkinter will try to create one for you (though you should never rely on this!). The widget that performs this job is called Tk.

The Tk widget exposes various window properties, such as the text within the top bar of the application, the size of the application, its position on screen, whether it can be resized, and even the icon which appears in the top right-hand corner (on Windows only).

Because of this feature exposure, it is very common for the main class of an application to inherit from the Tk widget, though any Tkinter widget can be subclassed to add program-specific functionality.

There is no set convention for what the subclass should be called. Some like to call it Root, some choose App, and others (such as myself) prefer to name it after the program itself. For example, a shopping list program would have a class called ShoppingList that inherits from Tk. Bear this in mind when looking through other sources of information on Tkinter.

Once you have a main window defined, you can begin adding other widgets into it. All other widgets must belong to a parent which has the ability to display them, such as a Tk or Frame. Each widget is only visible if its parent is. This allows us to group widgets into different screens and show or hide groups of them as need be.

Widgets are placed into their parents using special functions called geometry managers. There are three geometry managers available in Tkinter – pack, grid, and place. Let's take a look at each of them in detail.

Geometry managers

Geometry managers serve the purpose of deciding where in the parent widget to render its children. Each of the three geometry managers uses a different strategy and therefore takes different arguments. Let's go over each one in detail, looking at how it decides the positions of new widgets and what sort of arguments need to be provided.

pack

The pack geometry manager acts based on the concept of using up free space within the parent widget. When packing, you can specify at which end of the free space to put the widget, and how it will grow along with said free space (as the window itself grows and shrinks). The geometry manager than assigns widgets into said free space, leaving as little empty space as possible.

The pack geometry manager is primarily controlled by three keyword arguments:

  • side: On which end of the available space do you want to place the widget? The options are defined as constants within Tkinter, as LEFT, RIGHT, TOP, and BOTTOM.
  • fill: Do you want the widget to fill any available space around it? The options are also constants: X or Y. These are Cartesian, meaning X is horizontal and Y is vertical. If you want the widget to expand in both directions, use the BOTH constant.
  • expand: Should the widget resize when the window does? This argument is a Boolean, so you can pass True or 1 to make the widget grow with the window.

These are not the only arguments that can be provided to pack; there are others which handle things such as spacing, but these are the main ones you will use. The pack geometry manager is somewhat difficult to explain, but tends to create very readable code thanks to its use of words to describe positions.

The order in which widgets are packed matters greatly. Suppose you have two buttons which you wish to stack vertically, with one underneath the other. The first button, which you call pack(side=tk.BOTTOM) on, will be at the very bottom of the main window. The next widget, which is packed with side=tk.BOTTOM, will then appear above it. Bear this in mind if your widgets appear to be out of order when using pack as your geometry manager.

grid

The grid—as the name suggests—treats the parent widget as a grid containing rows and columns of cells. If you are familiar with spreadsheet software, grid will work in the same way. The grid lines will not be visible, they are just conceptual.

To specify the position within the grid, the row and column keywords are used. These accept integer values and begin at 0, not 1. A widget placed with grid(row=0, column=0) will be to the left of a widget at grid(row=0, column=1). Underneath these would sit a widget placed at grid(row=1, column=0).

To make a widget span more than one cell, use columnspan for a horizontal size increase and rowspan for a vertical increase. So, to make our hypothetical bottom widget sit below both, the full argument set would be grid(row=1, column=0, columnspan=2).

By default, a widget will sit in the center of its assigned cell(s). In order to make the widget touch the very edge of its cell, we can use the sticky argument. This argument takes any number of four constants: N, S, E, and W. These are abbreviations for North, South, East, and West. Passing in W or E will align the widget to the left or right, respectively. S and N will align to the bottom and top.

These constants can be combined as desired, so NE will align top right and SW will sit the widget bottom left.

If you wish for the widget to span the entire vertical space, use NS. Similarly, use EW to stretch to the full size in the horizontal direction.

If you instead want the widget to fill the whole cell edge to edge, NSEW will let you do this.

The pack and grid are both intended to lay out the entire content of a parent widget and apply different logic to decide where each new widget added should go. For this reason, they cannot be combined inside the same parent. Once one widget is inserted using pack or grid, all other widgets must use the same geometry manager. You can, however, pack widgets into one Frame, grid widgets into another, then pack/grid both of those Frame widgets into the same parent. 

place

Unlike pack and grid, which automatically calculate where each new widget is added, place can be used in order to specify an exact location for a particular widget. place takes either x and y coordinates (in pixels) to specify an exact spot, which will not change as the window is resized, or relative arguments to its parent, allowing the widget to move with the size of the window.

To place a widget at (5, 10) within the window, you would write widget.place(x=5, y=10).

To keep a widget in the direct center, you would use widget.place(relx=0.5, rely=0.5).

place also takes sizing options, so to keep a widget at 50 percent width and 25 percent height of the window, add (relwidth=0.5, relheight=0.25).

place is rarely used in bigger applications due to its lack of flexibility. It can be tiresome keeping track of exact coordinates for a widget, and as things change with the application, widgets may resize, causing unintended overlapping.

For a smaller window with only one or two widgets – say a custom pop-up message – place could be a viable choice of geometry manager, since it allows for very easy centering of said widgets.

One thing to note is that place can be used alongside pack or grid within the same parent widget. This means that if you have just one widget which you need to put in a certain location, you can do so quickly without having to restructure your already packed or gridded widgets.

To pack or to grid?

Using pack versus grid in your application is mostly down to personal preference. There doesn't seem to be a particularly dominant reason to use one over the other.

The main advantage of pack is the code tends to be very readable. pack uses words such as left and top to make it clear where the programmer wants the widget to go.

When using pack, sections of the window are also split using frames to allow for much greater control. When variables are named sensibly, this allows anyone changing the code to know exactly which part of a window the widget will end up in (by its parent Frame) and prevents them from having unexpected consequences when changing widgets, such as resizing a widget in the top-left corner of an application, knocking a widget at the bottom out of alignment.

The grid can also take advantage of Frame widgets too, but this can sometimes cause alignment issues.

Finally, pack works out widget positions based mainly on the argument and the order in which they are added. This means that when a new widget is added among existing ones, it is usually quite easy to get it into the correct spot. Simply adjust the order in which your widget.pack() calls occur. When using grid, you may need to change quite a few row and column arguments in order to slot the widget where you need it and keep everything else in their correct positions.

The great advantage of grid is its code simplicity to layout complexity ratio. Without the need to split your application into frames, you can save many lines of code and lay out a complicated window design with essentially just one line of code per widget.

You also don't need to worry about the order in which you add your widgets to their parent as the numerical grid system will apply regardless.

In the end, both prove to be good tools for the job and there is no need to use one if you prefer the other.

My personal preference is to use pack for main windows which may change quite a bit during development, and sometimes grid for smaller windows or layouts which are written in one go. Any additional windows for an application which would require more than two Frame widget are often better off being managed by grid for simplicity's sake.

Examples in this book will cover both grid and pack, so you will be able to practice both and decide which you prefer.

Getting going

Now that we have the basic understanding of the concept of widgets and how to add them into a window, it's time to put this into practice and make ourselves an application!

As with almost all programming examples, we will start with a Hello World application. Don't feel cheated though, it will have interactive aspects too! Let's begin with the most important step for any GUI application—showing a window. Start by opening your choice of text editor or IDE and putting in the following code:

import tkinter as tk

class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")

label = tk.Label(self, text="Hello World!")
label.pack(fill=tk.BOTH, expand=1, padx=100, pady=50)


if __name__ == "__main__":
window = Window()
window.mainloop()

Let's break this first step down. We begin by importing Tkinter and giving it the alias of tk for brevity. Every example in this book should include this line so that we have access to all of Tkinter's widgets, including the main window.

Speaking of widgets, we begin this example by subclassing Tkinter's main window widget—Tk. Doing so allows us to change various aspects of it, including the title which will display inside the window's top bar. We set the title to Hello Tkinter in this example.

Next, we want to display some text within our window. To do this, we use a Label widget. A Label widget is typically non-interactive and is used to display either text or an image.

When defining Tkinter widgets, the first argument is always the parent (sometimes called master) which will hold the widget. We use self to refer to our main window in this case. Afterward, we have a vast array of keyword arguments to use in order to change their properties. The text argument here will take a string which tells the label what to display. Our label will say Hello World!

Now that we have two widgets, we need to place the label inside of our main window (Tk) so that they both display. To do this with Tkinter, we utilize one of the geometry managers we covered earlier. For our first example, we will be using pack. Pack has been given the following arguments:

  • fill: This tells the widget to take all the space in both directions

  • expand: This tells the widget to expand when the window is resized

  • padx: Padding (empty space) of 100 pixels in the x direction (left, right)

  • pady: Padding of 50 pixels in the y direction (above, below)

With that, our Hello World is ready to run. In order to tell the main window to show itself, we call the mainloop method. This is all enclosed within the (hopefully familiar) if __name__ == "__main__" block. Utilizing this block allows widgets from one file to be imported into another file for reuse without creating multiple main windows.

Execute the code via your preferred method and you should see a little window appear. Congratulations! You have now written your first GUI application with Tkinter!:

Our Hello World application
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • The fundamentals of Python and GUI programming with Tkinter.
  • Create multiple cross-platform projects by integrating a host of third-party libraries and tools.
  • Build beautiful and highly-interactive user interfaces that target multiple devices.

Description

Tkinter is a modular, cross-platform application development toolkit for Python. When developing GUI-rich applications, the most important choices are which programming language(s) and which GUI framework to use. Python and Tkinter prove to be a great combination. This book will get you familiar with Tkinter by having you create fun and interactive projects. These projects have varying degrees of complexity. We'll start with a simple project, where you'll learn the fundamentals of GUI programming and the basics of working with a Tkinter application. After getting the basics right, we'll move on to creating a project of slightly increased complexity, such as a highly customizable Python editor. In the next project, we'll crank up the complexity level to create an instant messaging app. Toward the end, we'll discuss various ways of packaging our applications so that they can be shared and installed on other machines without the user having to learn how to install and run Python programs.

Who is this book for?

This book is for beginners to GUI programming who haven’t used Tkinter yet and are eager to start building great-looking and user-friendly GUIs. Prior knowledge of Python programming is expected.

What you will learn

  • Create a scrollable frame via theCanvas widget
  • Use the pack geometry manager andFrame widget to control layout
  • Learn to choose a data structurefor a game
  • Group Tkinter widgets, such asbuttons, canvases, and labels
  • Create a highly customizablePython editor
  • Design and lay out a chat window

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 25, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788622578
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 25, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788622578
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 116.97
Tkinter GUI Application Development Blueprints, Second Edition
€41.99
Tkinter GUI Application Development Cookbook
€32.99
Tkinter GUI Programming by Example
€41.99
Total 116.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Meet Tkinter Chevron down icon Chevron up icon
Back to the Command Line – Basic Blackjack Chevron down icon Chevron up icon
Jack is Back in Style – the Blackjack GUI Chevron down icon Chevron up icon
The Finishing Touches – Sound and Animation Chevron down icon Chevron up icon
Creating a Highly Customizable Python Editor Chevron down icon Chevron up icon
Color Me Impressed! – Adding Syntax Highlighting Chevron down icon Chevron up icon
Not Just for Restaurants – All About Menus Chevron down icon Chevron up icon
Talk Python to Me – a Chat Application Chevron down icon Chevron up icon
Connecting – Getting Our Chat Client Online Chevron down icon Chevron up icon
Making Friends – Finishing Our Chat Application Chevron down icon Chevron up icon
Wrapping Up – Packaging Our Applications to Share Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(3 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Vince Jan 29, 2021
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
TROPPO DIFFICILE QUESTO LIBRO, SOLO LEGGENDOLO E RILEGGENDOLO PIU VOLTE ALLA FINE CI SI CAPISCE QUALCOSA. DA MOLTISSIME COSE PER SCONTATE, SICURAMENTE NON UNA GUIDA PER BEGGINERS. SECONDO ME RISULTA SCOMODO DA USARE ANCHE PER DEGLI ADVANCED.
Amazon Verified review Amazon
Stefan Zee Oct 13, 2021
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Variablen ändern sich während des Ablaufs, so dass man eher Fehler such anstatt Dinge zu lernen.Komplett zusammenhängende Code erhält man erst gegen Registrierung auf einer weiteren Website. Schade.
Amazon Verified review Amazon
Scifud Jan 22, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This book was just what I was looking for with well explained examples, but as a Kindle book the examples are nearly useless. This is because python requires strict adherence to indentation but the way the text of the examples is displayed with the Kindle reader on my iPad the indentation is ambiguous. I spent several frustrating hours trying to determine if the errors my IDE was giving were due to improper code or to indentation. I got the first example to work by correcting an indentation error however the second example (a continuation of the first) creates an error that does not make sense.Until the code examples are formatted in a way that makes sense on Kindle I can not recommend this book in that form.I have returned the Kindle edition and have purchased the paperback. I will update this review after I have had a chance to review it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.