2016年4月6日 星期三

use python to write a GUI application based on GTK+3 framework

Recently I want to have a little application and I chose this solution:

python - the programming language
GTK+3 - the GUI framework
glade - the IDE to design the layout of the GUI application

glade could dump the layout drawn with glade IDE to a file in XML, which could be understood by GTK3+, so we could speed up our designing process.

The reason I chose GTK+3 is simple. It is because the glib on my OS** requires my glade should be 3.x instead of 2.x.***

** I use Ubuntu 14.04 64 bit
*** the syntax, "import gtk", is used to support GTK+2.x, and you could refer to this stackoverflow link for the details.




Step 1: use glade to draw the layout and dump it to XML.


Firstly launch glade, and then create a window by clicking the button "window" of the tool panel. Please note we should give the window a name, which its default is "window1", when creating it. This name will be also used for python gtk3+ program when the program tries to access the window object.

Save after drawing and the file will be in XML format.


Step 2: Write the python code


The overview flow of the python gtk+3 framework roughly looks like the following:
Use builder to get the window object, register signal and set up configuration etc. Finally executing Gtk main loop and waiting for events.

This is a snippet code of an example:

from gi.repository import Gtk
class HellowWorldGTK(object):
    """This is a Hello World GTK application"""
    def __init__(self):
        # layout generated by glade
        layout_filename = "layout.xml"
        builder = Gtk.Builder()
        builder.add_from_file(layout_filename)
        #builder.connect_signals(self)
        self.window = builder.get_object("window1")
        if self.window:
            self.window.connect("destroy", Gtk.main_quit)
        self.window.show_all()
if __name__ == "__main__":
    hwg = HellowWorldGTK()
    Gtk.main()

layout.xml is the file name saved in step1 with glade and "window1" is the window name mentioned in step1. Please pay attention to this line to quit the GTK main loop as destroying the window.

self.window.connect("destroy", Gtk.main_quit)

Without this line, the program will keep running after launching it and there is no way to use OS signal to terminate the process.

Step 3: executing


Save the snippet in Step2 as go.py. Execute go.py.


Please refer to Python GTK+3 Tutorial for more details.

沒有留言:

張貼留言