In this article we will look at creating a simple hello world program using wxPython. This program will create and display simple window with a big button on it. Up on clicking the button program will exit. Use the following code to create hello world program. You must already have wxPython library installed
Hello world program
import wx class MainWindow(wx.Frame): def __init__(self,parent): wx.Frame.__init__(self,parent,title="Hello World") self.killButton = wx.Button(self,label="Kill Me") self.killButton.Bind(wx.EVT_BUTTON,self.kill) self.Show() def kill(self,event): self.Close() print("Bye Bye cruel world") app = wx.App(False) frame = MainWindow(None) app.MainLoop()
We will go line by line here and try to explain what’s going on in this program. Most of the lines of self explanatory. If you are just getting started in programming the following explanation will be helpful.
- Import wxpython library
- Inherit from wx.Frame class. This is useful style for most of the programs that you will build. You can create one base frame or window and put rest of GUI widgets on top of it like Text controls, buttons,images, tables etc.
- Instantiate the inherited frame the desired title. parent argument is usually None for main windows.
- Create a button with label “Kill Me”. The first argument is parent. In this case we use “self” which is the main window we have just created.
- Bind the button click event (EVT_BUTTON) of the killButton to kill method. Whenever, EVT_BUTTON event is fired aka the killButton is clicked, kill method will be called.
- This line will cause the window to get displayed on screen. It’s customary to call this method after being done with construction of GUI i.e. create main window, place widgets, bind event like we did here.
- Create wxPython application by call wx.App. Every wxPython program must have this application.
- Start the main loop. Which will hand over control to wxPython library. This post explains why main loop has to be called.
This program will launch the following window. The button takes all the available space on the window since there are no other widgets. You need a few more lines of code to make the button look like what users are used to – small and horizontal. You can exit the program by clicking the button.