Getting started with wxPython
Getting Started
Getting started with wxPython
目录
A First Application: "Hello, World"
As is traditional, we are first going to write a Small "Hello, world" application. Here is the code:
Explanations:
app = wx.App(False) |
Every wxPython app is an instance of wx.App. For most simple applications you can use wx.App as is. When you get to more complex applications you may need to extend the wx.App class. The "False" parameter means "don't redirect stdout and stderr to a window". |
wx.Frame(None,wx.ID_ANY,"Hello") |
A wx.Frame is a top-level window. The syntax is x.Frame(Parent, Id, Title). Most of the constructors have this shape (a parent object, followed by an Id). In this example, we use None for "no parent" and wx.ID_ANY to have wxWidgets pick an id for us. |
frame.Show(True) |
We make a frame visible by "showing" it. |
app.MainLoop() |
Finally, we start the application's MainLoop whose role is to handle the events. |
Note: You almost always want to use wx.ID_ANY or another standard ID (v2.8) provided by wxWidgets. You can make your own IDs, but there is no reason to do that.
Run the program and you should see a window like this one:
Windows or Frames?
When people talk about GUIs, they usually speak of windows, menus and icons. Naturally then, you would expect that wx.Window should represent a window on the screen. Unfortunately, this is not the case. A wx.Window is the base class from which all visual elements are derived (buttons, menus, etc) and what we normally think of as a program window is a wx.Frame. This is an unfortunate inconsistency that has led to much confusion for new users.
Building a simple text editor
In this tutorial we are going to build a simple text editor. In the process, we will explore several widgets, and learn about features such as events and callbacks.
First steps
The first step is to make a simple frame with an editable text box inside. A text box is made with the wx.TextCtrl widget. By default, a text box is a single-line field, but the wx.TE_MULTILINE parameter allows you to enter multiple lines of text.
1 #!/usr/bin/env python
2 import wx
3 class MyFrame(wx.Frame):
4 """ We simply derive a new class of Frame. """
5 def __init__(self, parent, title):
6 wx.Frame.__init__(self, parent, title=title, size=(200,100))
7 self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
8 self.Show(True)
9
10 app = wx.App(False)
11 frame = MyFrame(None, 'Small editor')
12 app.MainLoop()
In this example, we derive from wx.Frame and overwrite its __init__ method. Here we declare a new wx.TextCtrl which is a simple text edit control. Note that since the MyFrame runs self.Show() inside its __init__ method, we no longer have to call frame.Show()explicitly.
Adding a menu bar
Every application should have a menu bar and a status bar. Let's add them to ours:
1 import wx
2
3 class MainWindow(wx.Frame):
4 def __init__(self, parent, title):
5 wx.Frame.__init__(self, parent, title=title, size=(200,100))
6 self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
7 self.CreateStatusBar() # A Statusbar in the bottom of the window
8
9 # Setting up the menu.
10 filemenu= wx.Menu()
11
12 # wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets.
13 filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
14 filemenu.AppendSeparator()
15 filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
16
17 # Creating the menubar.
18 menuBar = wx.MenuBar()
19 menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
20 self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
21 self.Show(True)
22
23 app = wx.App(False)
24 frame = MainWindow(None, "Sample editor")
25 app.MainLoop()
TIP: Notice the wx.ID_ABOUT and wx.ID_EXIT ids. These are standard ids provided by wxWidgets (see a full list here). It is a good habit to use the standard ID if there is one available. This helps wxWidgets know how to display the widget in each platform to make it look more native.
Event handling
Reacting to events in wxPython is called event handling. An event is when "something" happens on your application (a button click, text input, mouse movement, etc). Much of GUI programming consists of responding to events. You bind an object to an event using the Bind()method:
This means that, from now on, when the user selects the "About" menu item, the method self.OnAbout will be executed. wx.EVT_MENU is the "select menu item" event. wxWidgets understands many other events (see the full list). The self.OnAbout method has the general declaration:
Here event is an instance of a subclass of wx.Event. For example, a button-click event - wx.EVT_BUTTON - is a subclass of wx.Event.
The method is executed when the event occurs. By default, this method will handle the event and the event will stop after the callback finishes. However, you can "skip" an event with event.Skip(). This causes the event to go through the hierarchy of event handlers. For example:
When a button-click event occurs, the method OnButtonClick gets called. If some_condition is true, we do_something() otherwise we let the event be handled by the more general event handler. Now let's have a look at our application:
1 import os
2 import wx
3
4
5 class MainWindow(wx.Frame):
6 def __init__(self, parent, title):
7 wx.Frame.__init__(self, parent, title=title, size=(200,100))
8 self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
9 self.CreateStatusBar() # A StatusBar in the bottom of the window
10
11 # Setting up the menu.
12 filemenu= wx.Menu()
13
14 # wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets.
15 menuAbout = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
16 menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
17
18 # Creating the menubar.
19 menuBar = wx.MenuBar()
20 menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
21 self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
22
23 # Set events.
24 self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
25 self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
26
27 self.Show(True)
28
29 def OnAbout(self,e):
30 # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
31 dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK)
32 dlg.ShowModal()