Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

A lot of people have worked hard to simplify GUI programming in the Python environment. Standard
library packages help you create GUI widgets from your Python scripts and build your graphical
programs. Table 18.2 describes the most popular GUI packages used in the Linux world.


TABLE 18.2 Popular Linux GUI Packages

The tkinter package is one of the older graphical packages used in Python, and it’s therefore one
of the most popular packages. Since Python includes the tkinter package by default, it’s commonly
used to create graphical Python programs on the Raspberry Pi, and we use it in this hour.


Using the tkinter Package


Since the Raspberry Pi Python libraries include the tkinter package by default, we use it to
demonstrate creating GUI programs in Python scripts. Once you become familiar with how one
graphical library package works, it’s not too difficult to use any of the others.


You need to follow three basic steps to create a GUI application using the tkinter package:



  1. Create a window.

  2. Add widgets to the window.

  3. Define the event handlers for the widgets.


The following sections walk through each of these steps to show how you would build a GUI
application using tkinter in your Python scripts.


Creating a Window


In a GUI environment, everything revolves around a window. The first step to creating a GUI program
is to create the main window for your application, called the root window.


You do that by creating a Tk object, which controls all the aspects of your window. To create a Tk
object, you first need to import the tkinter library, and then you instantiate a Tk object, like this:


from tkinter import *
root = Tk()

This creates a main window object and assigns it to the variable named root. However, this default
window does not have any size, title, or features.


You next need to run a few default Tk object methods for the window to set up some of the window
features. Two common methods are the title() method to set a title for the window, which will
appear in the title bar at the top of the window, and the geometry() method, which sets the size of
the window. Here’s how you use them:


Click here to view code image

Free download pdf