Week 3 Pygtk Glade Development

Part 1: Just GTK

Needed Software

  • You have Python up and running on your computer, now you need PyGTK
    • GTK is the GUI library, PyGTK is the Python version
  • If you are running OS X, you need to virtualize either Windows, or a flavor of Linux to use GTK
  • If you're on Linux, run the following command
    • Substitute in yum for apt-get if on a RedHat based system
apt-get install python-gtk2
  • If you're on Windows, install the executable from here

Getting Started

  • The first thing we're going to do is create a HelloWorld class (adapted from the PyGTK 2 Tutorial)
#!/usr/bin/env python

# example helloworld.py

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

class HelloWorld:
    def hello(self, widget, data=None):
        print "Hello World"

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        gtk.main_quit()

    def __init__(self):
    # omitted!

    def main(self):
        gtk.main()

if __name__ == "__main__":
    hello = HelloWorld()
    hello.main()
  • We want the init to set up the logic to create a program like:
    • When the button is pressed, we want Hello World to be printed to the command-line
helloworld.png
  • Name all of the possible set up that would be necessary for the program to run.
  • The following is the completed init
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

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

        self.window.set_border_width(10)

        self.button = gtk.Button("Hello World")

        self.button.connect("clicked", self.hello, None)
        self.button.connect_object("clicked", gtk.Widget.destroy, self.window)

        self.window.add(self.button)

        self.button.show()
        self.window.show()
  • GTK uses signals for events
    • Why do they use signals instead of us checking when a button is pressed?
    • self.hello (the function) is called a call-back function
  • Where did self.window come from?
  • Notice the last couple of lines of the init
    • Hide/show allows for a dynamic UI'
  • What would happen if we didn't connect the gtk.Widget.destroy signal to the application?

Assignment

  • Write a GUI Python application to recreate tic-tac-toe
  • Use the PyGTK API reference to create a table of buttons that can be clicked to mark them as an 'x' or an 'o'
  • Designate a winner however you'd like
  • Should look something like this:
tictactoe.png

Moving on

  • How does GTK compare to other UI libraries you have used in the past?
    • Similarities/Differences
  • Does writing a GUI completely in Python make sense?
    • No - that's why we use a nifty program called Glade
    • See Part 2!
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License