Creating a simple GUI window using wxpython
Let’s get started with wxpython. We will see how to create a simple window named Hello World!.
First, get wxpython.
Windows: Download it from here.
Linux :
sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-doc wx2.8-examples wx2.8-headers wx2.8-i18n libwxgtk2.8-dev libgtk2.0-dev
We will have two python files for this example. Those are :
Now here is the code for the window.py.
Let’s go line by line.
First, we create an application object to start the application.
Then we create a window and a panel object. A panel is what wraps the widgets in the window. It is a transparent object which you can’t see.
Next we call the class Mypanel, and pass the window and panel objects as arguments.
After that we show the window with show method on the window object.
And finally we run a loop through the application object to hold the GUI until we send a close message.
Next let’s look at class_Mypanel.py.
Here is the structure of the file.
-
__init__:
This is the constructor method, which is called at the time of object creation. In this method, we create all the widgets that we want in our window.
First we set some instance variables for window and panel objects and also set some properties for the panel. We have assigned the objects to instance variables so that we can access them in the instance methods like in close method in our example.
Then we create a button. We bind an event to this button, which causes the close method to be called whenever that event is triggered by clicking the button.
The first line calls the wx button constructor which takes the first argument panel as its parent. A title, an id, and position and size of the button are other arguments.
In next three lines, we set the bg color, fg color and help string for button and in the next line we bind the close method to button with a button event. The last line positions the window on the center of the screen.
-
close:
This method is used to close the window. It is called when close button is clicked. It contains a single line which destroys the window object.
That’s all. Now when you run the window.py, you see a window with a close button.
We’ll see next how to create different widgets, like text areas, check boxes, radio buttons and different properties which can be applied on the widgets. We will also see how to add images in the window and setting icon for the window and much more in upcoming posts.
Comments
Leave a comment