Adding the main frame
Most applications have some sort of main window that they want to show to allow their users to interact with the software. In wxPython, this window is called a frame. The frame is the main top-level container and the base for building most user interfaces in wxPython. This recipe will show how to create a frame and add it to an application.
How to do it…
You can do this by performing the following steps:
- Start by making a subclass of
wx.Frame
with the following code:class MyFrame(wx.Frame): def __init__(self, parent, title=""): super(MyFrame, self).__init__(parent, title=title) # Set an application icon self.SetIcon(wx.Icon("appIcon.png")) # Set the panel self.panel = wx.Panel(self)
- Next, create an instance of the frame and show it using the following code:
class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(None, title="Main Frame") self.frame.Show() return True
- Run the script and take a look at what we made:
How it works…
The Frame
class creates a top-level window that can be used to present any number of other controls. A frame can be created without any parent window and will remain in the application until it is dismissed by the user.
In this recipe, we set up a couple of items on the MyFrame
class:
- We called
SetIcon
to set the custom application icon on the title bar of the frame. This icon was created from theappIcon.png
file, which exists in the same directory as the script. - We created a
Panel
object and set the frame as its parent object. A panel is a plain rectangular control used to contain other controls and is shown as the rectangular area inside the frame's borders. A panel must have a parent window in order to be created.
Finally, in the App
object's OnInit
method, we created an instance of the frame specifying the title that we wanted to show in the frame's title bar and then called its Show
method to display it on the screen. This recipe can be used as the preparation to create any wxPython application.
There's more…
The wx.Frame
constructor has several style flags that can be specified in its constructor to modify its behavior and appearance.
Style flag |
Description |
---|---|
|
This flag is a bit mask of all the other flags described in the following sections |
|
This displays the minimize button on the title bar |
|
This displays the maximize button on the title bar |
|
This allows the frame to be resized by the user |
|
This displays a title caption on the frames title bar |
|
This displays the close button on the title bar |
|
This displays a system menu (the menu that appears when clicking on the frame icon on Windows) |
|
This eliminates the flicker caused by background repainting (Windows only) |
These style flags can be passed in any combination using a bitwise operator to turn off any of the features that you may not want to provide on all frames. Multiple flags can be combined using a bitwise or operation.