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

(singke) #1
FIGURE 18.1 A default Tk window with no widgets.

Congratulations! You’ve just written a Python GUI program! There aren’t any widgets to interact
with, so to close out the window, you have to click the X in the upper-right corner of the window.
Next you will start adding some widgets to your window to make things happen.


Adding Widgets to the Window


After you’ve created the root window, you’re ready to start working on the widgets for your interface.
There are three steps involved with adding widgets to a window:



  1. Create a frame template in the root window.

  2. Define a positioning method to use for placing widgets in the frame.

  3. Place the widgets in the frame, using the positioning method you’ve chosen.


The following sections walk through these steps.


Creating a Frame Template


The first step in the process of adding widgets to your window is to create a template for the window
widget layout. The tkinter package uses the Frame object to create an area for you to place
widgets in the window. However, you don’t use the Frame object directly in your window code;
instead, you must create a child class to define all the window methods and attributes, based on the
Frame class. (For more info on child classes, see Hour 15, “Employing Inheritance”). While you can
call your Frame object child class anything you want, the most popular name for this class is
Application, as shown here:


class Application(Frame):

After you create the child class, you need to create a constructor for it. Remember from Hour 14,
“Exploring the World of Object-Oriented Programming,” that you define a constructor by using the
init() method. This method uses the keyword self as the first parameter, and it takes the
root Tk window object that you created as the second parameter. This is what links the Frame
object to the window.


You now have a basic template that you can use to create a window Frame class:


Click here to view code image


class Application(Frame):
"""My window application"""
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()

The class definition to create the window and frame isn’t very long, but it is somewhat complicated.
The constructor that you built for the Application class contains two statements. The super()
statement imports the constructor method from the parent Frame class for the Application class,
passing the root window object. The last statement in the constructor defines the positioning method
used for the frame. This example uses the tkinter grid() method. (You’ll learn more about that
feature in the next section.)


Now that you have your Application class template, you can use it to create a window. Listing
18.2 shows the script1802.py file, which is a basic code template that you’ll use to create a

Free download pdf