Creating an application object
The App
object is an object that all wxPython applications must create before any other GUI object. This object creates the application and provides its main event loop, which is used to dispatch events and connect actions in the UI with the actions in your programs.
This recipe will introduce how to create a minimal wxPython application, which will be used as foundation for every other recipe in this book.
How to do it…
Perform the following steps:
- Make the script as follows:
import wx class MyApp(wx.App): def OnInit(self): wx.MessageBox("Hello wxPython", "wxApp") return True if __name__ == "__main__": app = MyApp(False) app.MainLoop()
- Run the script and take a look at the result:
How it works…
There are three things to take note of in this simple application: the first, we created a subclass of the wx.App
object; the second, we overrode the OnInit
method; and the third, we called the MainLoop
method of the application object. These simple steps set up the base for any application.
The OnInit
method is called by the application's MainLoop
method when it is started and provides an entry point to start up the main logic and user interface of your application. In this example, we just used it to show a simple pop-up dialog box. The application's MainLoop
method continues to run until the last window associated with the application is closed. The OnInit
method must return true
in order to continue the initialization of the MainLoop
applications.
The MainLoop
method processes and dispatches all the messages that are needed to present the UI and direct messages for user actions initiated with button clicks. When the OK button is clicked on the dialog, it sends a message that is dispatched by the MainLoop
method to close the dialog. In this example, once the dialog has returned, OnInit
will also return, and there will be no window objects remaining. So, the application's MainLoop
method will return as well, and this script will exit.
There's more…
Though generally the wx.App
object is created as we did in this example, the class constructor also has four optional keyword arguments that can be used to modify some of its behavior:
wx.App(redirect=False, filename=None, useBestVisual=False, clearSigInt=True)
The four optional keyword arguments are as follows:
redirect
: If set toTrue
,stdout
is redirected to a debug windowfilename
: If redirect isTrue
and this is notNone
, thenstdout
can be redirected to a file specified by this argumentuseBestVisual
: This specifies whether the application should try to use the best visuals provided by the underlying toolkit. (This has no effect on most systems.)clearSigInt
: Setting this toTrue
will allow the application to be terminated by pressing Ctrl+C from the command line.
See also
- The Handling errors gracefully recipe in Chapter 10, Getting Your Application Ready for Release, provides additional information on methods that can be overridden in
wx.App
.