Working with applications and frames

Once you've imported the wx module, you can create your application and frame objects. Every wxPython program must have one application object and at least one frame object. These objects will be discussed in detail in chapter 2. For now, you just need to know that the application object must be an instance of wx.App or of a subclass you define where you declare an OnInit() method. The OnInit() method will be called by the wx.App parent class when your application starts.

Subclass the wxPython application class

Here is how we defined our wx.App subclass:

class MyApp(wx.App):

def OnInit(self):

frame = wx.Frame(parent=None, id=-1, title="Bare")


return True

We named our class "MyApp," which is a common convention, but any valid Python class name would do.

The OnInit() method is where you'll most often create frame objects. But you won't usually directly create instances of wx.Frame as we did here. Instead, you'll define your own wx.Frame subclass the same way we defined our own wx.App subclass. (You'll see an example in the next section.) We'll explore frames in detail in the next chapter, so for now we'll simply point out that the wx.Frame constructor accepts several parameters. Of the three we supplied, only the first is required, while the rest have default values.

Invoking the Show() method makes the frame visible. If we had left that out, the frame would have been created, but we wouldn't be able to see it. We can toggle the frame's visibility by calling Show() with a Boolean parameter:




# Make the frame invisible.

# True is the default parameter value.

# Equivalent to frame.Show(False).

Define an application initialization method

Notice that we didn't define an_init__() method for our application class. In

Python, this means that the parent method, wx.App.__init__(), is automatically invoked on object creation. This is a good thing. If you define an_init_()

method of your own, don't forget to call the_init_() of the base class, like this:

class App(wx.App):

# Call the base class constructor. wx.App.__init__(self)

If you forget to do so, wxPython won't be initialized and your OnInit() method won't get called.

Create an application class instance and enter its main event loop

The final step is to create an instance of the wx.App subclass, and invoke its Main-Loop() method:

That's it. Once the application's main event loop processing takes over, control passes to wxPython. Unlike procedural programs, a wxPython GUI program primarily responds to the events taking place around it, mostly determined by a human user clicking with a mouse and typing at the keyboard. When all the frames in an application have been closed, the app.MainLoop() method will return and the program will exit.

Was this article helpful?

0 0

Post a comment