Book Image

Python GUI Programming Cookbook

By : Burkhard Meier
Book Image

Python GUI Programming Cookbook

By: Burkhard Meier

Overview of this book

Table of Contents (18 chapters)
Python GUI Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding a label to the GUI form


Getting ready

We are extending the first recipe. We will leave the GUI resizable, so don't use the code from the second recipe (or comment the win.resizable line 4 out).

How to do it...

In order to add a Label widget to our GUI, we are importing the ttk module from tkinter. Please note the two import statements.

# imports                  # 1
import tkinter as tk       # 2
from tkinter import ttk    # 3

Add the following code just above win.mainloop() located at the bottom of recipes 1 and 2.

# Adding a Label           # 4
ttk.Label(win, text="A Label").grid(column=0, row=0) # 5

Running the code adds a label to our GUI:

How it works...

In line 3 of the above code, we are importing a separate module from tkinter. The ttk module has some advanced widgets that make our GUI look great. In a sense, ttk is an extension within tkinter.

We still need to import tkinter itself, but we have to specify that we now want to also use ttk from tkinter.

Note

ttk stands for 'themed tk". It improves our GUI look and feel.

Line 5 above adds the label to the GUI, just before we call mainloop (not shown here to preserve space. See recipes 1 or 2).

We are passing our window instance into the ttk.Label constructor and setting the text property. This becomes the text our Label will display.

We are also making use of the grid layout manager, which we'll explore in much more depth in Chapter 2, Layout Management.

Note how our GUI suddenly got much smaller than in previous recipes.

The reason why it became so small is that we added a widget to our form. Without a widget, tkinter 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.

There's more...

Try resizing and maximizing this GUI with a label and watch what happens.