PyGTK Hello World or: How I learned to write my first GUI application on Ubuntu?

There are so many things I like about Ubuntu and I can write in extent about all those. My focus is in this post is Python. Python is easy to learn. So easy that one can write GUI apps in just 2 minutes. The title for the post has also indicated this(and is somewhat similar to Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb ). I am a learn by doing person and this post is for same kind of persons. So first the code, with very little or no explanation, shows a hello world widow:

Hello World using Python & PyGTK
Hello World using Python & PyGTK
#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk

class Whc:
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title("Hello world!")
		self.label = gtk.Label("H3ll0 W0rld!")
		self.window.add(self.label)
		self.label.show()
		self.window.show()

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	base = Whc()
	base.main()

…and then how I tweaked it

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
import os
import commands

class Whc:
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title("Your \"fortune\"")
		self.window.set_default_size(200,100);
		f=commands.getoutput("fortune")
		self.label = gtk.Label(f)
		self.window.add(self.label)
		self.label.show()
		self.window.show()

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	base = Whc()
	base.main()

…and then output

Displays a random fortune cookied in GUI
Displays a random fortune cookied in GUI

…and now the analysis. 🙂

The code given above uses PyGTK, GTK bindings for Python, GTK, OS and Command module. The OS and Command module is just to fetch the output of fortune command. fortune is a Linux command, more can be found here and may have to be installed, the package is fortune-mod. The Python code is plain English, create a TOPLEVEL window, see for more. In the first code listing another GTK widget Label has been added. The Label contains a snippet of readonly text rendered on Window and in first snippet the text string is legendary, “H3ll0 W0rld!” in L33T. The string in 2nd code snippet is replaced by output of fortune command for which I utilised command and os modules. Easy!!!

This post was lying in drafts for more than 15 months.