[pygtk] outputting answer to GUI

Christopher Spears cspears2002 at yahoo.com
Wed Jul 19 09:04:20 WST 2006


Here is a script that I wrote that converts between
degress Celsius and Fahrenheit:

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
	
class Conversion_GUI:
	def get_text(self, widget, entry):
		entry_text = entry.get_text()
		temp = float(entry_text)
		return temp
		
	def convert_to_celsius(self, temp):
		return (temp - 32)/1.8
		
	def convert_to_fahrenheit(self, temp):
		return temp * 1.8 + 32
		
	def print_temp(self, widget, entry, rb1):
		temp = float(entry.get_text())
		if rb1.get_active():
			val = '%.2f C' % self.convert_to_celsius(temp)
		else:
			val = '%.2f F' % self.convert_to_fahrenheit(temp)
		print "Degrees temp: ", val
		
		
	def __init__(self):
		self.temp = 0
		
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", lambda w:
gtk.main_quit())
		self.window.set_title("Convert Temperatures")
		self.window.set_default_size(200,100)
		
		entry = gtk.Entry()
		entry.set_max_length(10)
		entry.set_text("0")
		label = gtk.Label("Enter Temp: ")
		label.set_justify(gtk.JUSTIFY_LEFT)
		entry.show()
		label.show()
		
		rb1 = gtk.RadioButton(None, "Fahrenheit")
		rb2 = gtk.RadioButton(rb1,"Celsius")
		rb1.show()
		rb2.show()
		
		box1 = gtk.VBox(False, 0)
		box2 = gtk.HBox(False, 0)
		box2.pack_start(rb1, False, False, 0)
		box2.pack_start(rb2, False, False, 0)
		box1.pack_start(box2, False, False, 0)
		
		box3 = gtk.HBox(False, 0)
		self.window.add(box1)
		
		box3.pack_start(label, False, False, 0)
		box3.pack_start(entry, True, True, 0)
		box1.pack_start(box3, False, False, 0)
		
		entry.connect("activate", self.print_temp, entry,
rb1)
		quit_button = gtk.Button("Quit")
		quit_button.connect("clicked", lambda
w:gtk.main_quit())
		convert_button = gtk.Button("Convert")
		convert_button.connect("clicked", self.print_temp,
entry, rb1)
		convert_button.show()
		quit_button.show()
		
		box3.pack_start(convert_button, False, False, 0)
		box3.pack_start(quit_button, False, True, 0)
		
		box3.show()
		box2.show()
		box1.show()
		self.window.show()
		
	def main(self):
		gtk.main()
		return 0
	
if __name__ == '__main__':
	convert = Conversion_GUI()
	convert.main()

Right now, the script simply prints the answer to the
screen, but I think printing to the GUI would be more
logical.  I have been going through the PyGTK tutorial
and docs and have not found a widget that exists
solely to accept information that would normally print
to the screen.  What should I use?  Can I modify a
label to do the job?


More information about the pygtk mailing list