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

(singke) #1
4: class Application(Frame):
5: """Build the basic window frame template"""
6:
7: def __init__(self, master):
8: super(Application, self).__init__(master)
9: self.grid()
10: self.create_widgets()
11:
12: def create_widgets(self):
13: self.label1 = Label(self, text='Welcome to my window!')
14: self.label1.grid(row=0, column=0, sticky= W)
15:
16: root = Tk()
17: root.title('Test Application window with Label')
18: root.geometry('300x100')
19: app = Application(root)
20: app.mainloop()

The create_widgets() method contains two lines of code to define a Label widget object for
the window. Line 13 defines the actual Label object, and line 14 applies the grid() method to
position the Label widget in the window. (Yes, that’s correct: You need to specify the placement
method for both the Frame object and the individual widget objects inside the frame.)


When you run the script1803.py file, you see a window like the one shown in Figure 18.2.


FIGURE 18.2 Displaying the simple test window.

The window contains the Label object that you defined in the create_widgets() method, and
the label text appears in the window frame.


Defining Event Handlers


The next step in building a GUI application is to define the events that the window uses. Widgets that
can generate events (such as when the application user clicks a button) use the command parameter
to define the name of a method Python calls when it detects the event.

Free download pdf