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
self.killButton = wx.Button(self,label="Kill Me")
print("Bye Bye cruel world")
app = wx.App(False)
frame = MainWindow(None)
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.