PyGTK - Hello World



Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code.

import gtk

The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window.

class PyApp(gtk.Window):

Define the constructor and call the show_all() method of the gtk.window class.

def __init__(self):
   super(PyApp, self).__init__()
   self.show_all()

We now have to declare the object of this class and start an event loop by calling its main() method.

PyApp()
gtk.main()

It is recommended we add a label “Hello World” in the parent window.

label = gtk.Label("Hello World")
self.add(label)

The following is a complete code to display “Hello World”

import gtk

class PyApp(gtk.Window):
   def __init__(self):
      super(PyApp, self).__init__()
      self.set_default_size(300,200)
      self.set_title("Hello World in PyGTK")
      label = gtk.Label("Hello World")
      self.add(label)
      self.show_all()
PyApp()
gtk.main()

The implementation of the above code will yield the following output −

Hello World PyGTK
Advertisements