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
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.
In this post we will go over the topic of easy way to install wxpython. The following command will install wxpython easily in python3.
pip install wxpython
Older versions of wxpython can be installed by downloading binaries (for windows) from sourceforge . The binaries are available for both Windows and MacOS.
The pip install command should work on linux also. However, if you are stuck on old linux vesions. You can try installing wxpython using your distro’s package manager like apt-get or yum. You can search for exact version and package name available on your platform using the following commands for debian variants.
apt-cache search wxpython
┌──(kali㉿kali)-[~] └─$ apt-cache search wxpython gnumed-client - medical practice management - Client psychopy - environment for creating psychology stimuli in Python pyscanfcs - scientific tool for perpendicular line scanning FCS python3-genx - differential evolution algorithm for fitting python3-opengl - Python bindings to OpenGL (Python 3) python3-pyface - traits-capable windowing framework python3-squaremap - wxPython control to display hierarchic data as nested squares python3-wxgtk-media4.0 - Python 3 interface to the wxWidgets Cross-platform C++ GUI toolkit (wx.media) python3-wxgtk-webview4.0 - Python 3 interface to the wxWidgets Cross-platform C++ GUI toolkit (wx.html2) python3-wxgtk4.0 - Python 3 interface to the wxWidgets Cross-platform C++ GUI toolkit soundgrain - Graphical interface to control granular sound synthesis modules wxglade - GUI designer written in Python with wxPython wxpython-tools - Tools from the wxPython distribution
Use the following command to check if the installation is successful or not.
PS C:\Users\godson> python
Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
'4.1.1 msw (phoenix) wxWidgets 3.1.5'
As shown above it should print current version of wxpython installed if the installation is successful.
Continuing our series of desktop GUIs, in this post we are going to go over the topic of building a small hello world program using Python Tkinter.
What is Tkinter ?
Tkinter is python wrapper/binding to Tk library. Tk was developed as GUI library for Tcl language by John Ousterhout. For many other high level language authors coming to programming scene in 1990s this seemed like easy tool to capitalize on in bringing GUI library to their language. That’s why you can find many different language bindings to Tk. Tk brought easy GUI building to programming masses.
Often times many people write off Tk or Tkinter as ugly old GUI library. Their claims are not completely unfounded. But, Tk in recent times made strides to bring modern look by implementing Tile, themeing engine. Tile is also called as ttk. With ttk in place look and feel issues of Tk are addressed.
But, Tkinter still lags behind in terms available collection of default widgets compared to other libraries like PySide or wxPython . However, Tkinter is still a good candidate if you quickly want to dish out a GUI without having programming styles imposed on you. (You will see these style restrictions in our next posts about wxPython and PySide)
Now, we will go over building a simple hello world program using Tkinter. In this program we will create a simple window with “Hello world” text in it. And a button that say “Kill Me”. Clicking that button will cause the python program to exit.
from Tkinter import *
root = Tk()
l = Label(text="Hello world", font=("Helvetica", 20))
b = Button(text="Kill Me", command=sys.exit)
That import * line saves your some typing.
root = Tk()
This line instantiates Tk and creates main window of the program. Next we create a Label (a widget which displays text ) and call it’s pack method. pack is one three available layout methods provided by Tkinter (rest of the two being grid and place). The widget will not show up until you call pack. Next, we create a Button widget and pack it, similar to that of Label. The interesting point to note while creating button widget is, we provide command argument to it with a reference of sys.exit function. A newbie mistake that is often made is, passing function with () next to it. That will cause the target function to be invoked immediately. You are only supposed to pass the reference of function and Tkinter will call it when button is pressed. So, when this “Kill Me” button is pressed sys.exit will be called and program exits. One, last important line to notice is root.mainloop() . This line sets the event monitoring loop in motion and Tkinter take control of the program from here.
In this post we will go over some of the basic and common constructs that you come across while building GUI programs almost in any language or library. The following are some of the common items that I can think of
Loop or Mainloop as it is called in some GUI libraries is one of the most common element of all GUI programs. In a GUI program this is usually called at the at end of constructing the all the items (widgets) in program. When you call the mainloop, it takes over the control and keeps running until you terminate the GUI.
The main purpose of loop is to poll for user input (mouse and keyboard actions) and fire events which your program can handle in asynchronous way. Following diagram explains loop in simple terms.
As you can see from the above diagram the GUI loop keeps polling for user input. If there is any event via mouse or keyboard or other input devices (joysticks, game pads ) when input is available loop gives control to callback functions that are bound to input events. Loop keeps running until the main window (also called parent window) exits. Once the main window is destroyed the loop exits and gives control back to your code. In most cases end of the mainloop would be end of many GUI programs.
GUIs are collection of widgets. Example of widgets are button, scroll bar, check box etc. Widget is an element of user interaction. Their main purpose is to display or collect information from user. A label displays text to user. A text input widget collects text from user. One way to decide the richness of GUI tool kits is to look at how many widgets they offer. The more widgets a library offers you the better it is for you. So, that you don’t have to write extra code to implement custom widgets. Widgets usually are sub classes of a Widget parent class. So, most of the widgets inherit properties of widget class in respective GUI libraries. In some GUI libraries main window also has properties of a widget.
When ever user presses a button or enters text using keyboard those actions generate events in GUI libraries. GUI libraries provide a way to hook into these events so that your program can respond to user actions. The event hooking/binding style differs from library to library. But, the aim is same across all libs, that is to provide programmer a way to respond to user input.
Layout facilities provided by GUI libs helps to make programmer’s life easier when placing widgets in main window. Layouts are simple rules you use to convey to GUI library on how you would like your widgets to be laid out on screen. Instead of manually placing widgets on screen by specifying distance units and placement pixel positions, once you construct your widgets you hand them over to certain layout scheme to let GUI library handle the placement. The benefits are, layouts will take care of expansions, size proportions and other nitty-gritty detail of placing your widgets in orderly way.
The layout features provided by libraries vary greatly. You often have to pick the one that suits your needs. These layouts can be mixed in order to achieve the placement and look you want.
If you want to build desktop GUIs, Python is right candidate to pick. It offers you plethora of GUI libraries compared to any other language. So, there are high number of chances that, some library in there fits your bill which is readily available, in whole of lot of GUI libs python has to offer. Following is a list of some of the popular GUI libs
(Complete list of available libraries can be found on python wiki page.)
All of the above mentioned ones are cross-platform capable libraries. So, that you don’t have to rewrite any part of your GUI and gladly run it across all the main contenders Windows, Linux and Mac . There are other platform specific ones like win32gui , WinForms using IronPython. But, it helps to stick with cross-platform capable libs to avoid extra work when building your app for other platforms.
Over the next few posts I’ll present you with examples of simple hello world programs using above mentioned list of libraries.
Usually the best way to build your GUI application is to write compute intensive part (if there is any ) of your business logic in low level languages like C/C++ and then write GUI code using the above mentioned Python libs. This saves you lot of time and energy. As, compared to low level languages, in Python you get the benefit of automatic memory management and you only have to write less number of lines of code.