34.1 Python and GTK

The simplest Python program using GTK is:

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

window = gtk.Window ()
window.add(gtk.Label("Hello World"))
window.connect("delete-event", lambda a,b: gtk.main_quit())
window.show_all()
gtk.main()

Cut and paste this into a Python running from the command line and a little window should pop up!

With a little more functionality, using a callback to do something when a button is pressed:

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

greetings = ["Goodbye Cruel World", "I'm Leaving You Today", 
             "Goodbye, Goodbye, Goodbye"]

def select_greeting (greet):
    return greet[random.randint(0, len(greet)-1)]

def hello_button_clicked(button, label):
    label.set_text(select_greeting(greetings))

window = gtk.Window ()
vbox = gtk.VBox ()
button = gtk.Button("Welcome to the Machine")
label = gtk.Label (select_greeting (greetings))

window.add(vbox)
vbox.add(label)
vbox.pack_start(button, False, False)

window.connect("delete-event", lambda a,b: gtk.main_quit())
button.connect("clicked", hello_button_clicked, label)

window.show_all()
gtk.main()  


Your donation will support ongoing availability and give you access to the PDF version of the book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.