Adding Widgets using the Raspberry Pi 3

With Tkinter all the graphical controls that can be included in the application window, such as buttons or checkboxes, are referred to as “widgets”. Each widget is listed in the table below, together with a brief description:




The tkMessageBox widget is defined in its own module which must be imported separately. It is demonstrated later in this chapter.



The default window’s title of “tk”, as in the previous example, can be changed by specifying a string within the parentheses of the window object’s title() method.

A label object is created by specifying the window name and text=string as arguments to a Label() constructor. The label can then be added to the window using its pack() method. Optionally, this can specify padding with padx=n and pady=n values.


Step 1
Launch a plain text editor and begin a new Python program by locating the interpreter
#! /usr/bin/env python

Step 2
Next, import the Tkinter module to make its attributes and methods available
from Tkinter import *

Step 3
Now, create a window object by calling the constructor
window = Tk()

Step 4
Specify a title to replace the default window title
window.title( ‘Label Example’ )

Step 5
Then, create a label object
label = Label( window , text = ‘Hello World!’ )

Step 6
Add the label to the window with both horizontal and vertical padding


Padding values can also be specified as a tuple to apply the padding unequally. For example with padx = (20, 80).

label.pack( padx = 100 , pady = 50 )

Step 7
Finally, add the loop to capture this window’s events

Step 8
Save the file and make it executable, then run the program to see an application window appear bearing the specified title and the padded label







Notice that the padding has been applied all around the text, with 100 pixels each side horizontally and 50 pixels each side vertically, so the text is centered. The overall window size automatically assumes the proportions of its contents, so in this case the window fits snugly around the label.





Raspberry Pi 3 in easy steps 9781840787290

Want to know more?

For the complete Raspberry Pi 3 guide, all in the trusted In Easy Steps style, click here. In full-colour and straightforward, jargon-free language, Raspberry Pi 3 in Easy Steps enables complete beginners to create their very own computer programs with the Scratch visual programming environment. It also instructs programming in the high-level (human-readable) Python programming language, which is processed by the Python ‘interpreter’ to produce results fast.