16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 12 ■ GRAPHICAL USER INTERFACES 273<br />

Because there are no windows the user can interact with, the program exits immediately.<br />

■Note As you can see from this example, the methods in the wx package are all capitalized, contrary <strong>to</strong><br />

common practice in <strong>Python</strong>. The reason for this is that the method names mirror method names from the<br />

underlying C++ package, wxWidgets. Even though there is no formal rule against capitalized method or function<br />

names, the norm is <strong>to</strong> reserve such names for classes.<br />

Creating Windows and Components<br />

Windows, also known as frames, are simply instances of the wx.Frame class. Widgets in the wx<br />

framework are created with their parent as the first argument <strong>to</strong> their construc<strong>to</strong>r. If you’re<br />

creating an individual window, there will be no parent <strong>to</strong> consider, so simply use None, as<br />

you see in Listing 12-1. Also, make sure you call the window’s Show method before you call<br />

app.MainLoop—otherwise it will remain hidden. (You could also call win.Show in an event<br />

handler; I discuss events a bit later.)<br />

Listing 12-1. Creating and Showing a Frame<br />

import wx<br />

app = wx.App()<br />

win = wx.Frame(None)<br />

win.Show()<br />

app.MainLoop()<br />

If you run this program, you should see a single window appear, similar <strong>to</strong> that in<br />

Figure 12-2.<br />

Figure 12-2. A GUI program with only one window<br />

Adding a but<strong>to</strong>n <strong>to</strong> this frame is about as simple as it can be—simply instantiate wx.But<strong>to</strong>n,<br />

using win as the parent argument (see Listing 12-2).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!