#!/usr/bin/env python
import gtk, gtk.glade, random

# any function in handlers class that is mentioned in
# a glade signal handler will automatically executed
# as appropriate
class Handlers:
	
	def on_window1_destroy(self,widget):
		gtk.main_quit()
		return False

	def on_button1_clicked(self,widget):
		msgtxt="You were correct!"
		if self.oa=="/": a=self.r1/self.r2
		if self.oa=="*": a=self.r1*self.r2
		if self.oa=="+": a=self.r1+self.r2
		if self.oa=="-": a=self.r1-self.r2
		try:
			v=int(ui.entry1.get_text())
		except:
			v=0
			ui.entry1.set_text("")
			return
		if a!=v:
			msgtxt="You were Wrong!!!"
		msg=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, msgtxt)
		r=msg.run()
		msg.destroy()
		self.make_sum(None)
		ui.entry1.set_text("")
		ui.entry1.grab_focus()

	def make_sum(self,widget):
		# called by window show signal too
		self.r1=random.randint(1,9)
		self.r2=random.randint(1,9)
		s={0:"+",1:"-",2:"*",3:"/"}
		self.oa=s[random.randint(0,3)]
		if self.oa=="/":
			self.r1=self.r2*self.r1
		ui.op1.set_text(str(self.r1))
		ui.op2.set_text(str(self.r2))
		ui.opand.set_text(self.oa)

# autoloads all the widgets and allows easy
# widget lookup
class WidgetWrapper:

   	def __init__(self,filename,handlers):
		self.widgets = gtk.glade.XML(filename)
		self.widgets.signal_autoconnect(handlers)

	def __getattr__(self, attr):
		new_widget = self.widgets.get_widget(attr)
		if new_widget is None:
			raise AttributeError, 'Widget %r not found' % attr
		setattr(self, attr, new_widget)
		return new_widget



# utility function to easily change a widgets font
def setFontParams( widget, size=None, weight=None):
	context = widget.get_pango_context()
	font = context.get_font_description()
	if size is not None:
		font.set_size(int(size)*1024)
	if weight is not None:
		font.set_weight(weight)
	widget.modify_font(font)


# as the Handlers class has attributes you should *only*
# call functions through the instance used by the
# widget wrapper 
events_cb=Handlers()

# all the gui widgets are now availible in the
# ui object as attributes
ui = WidgetWrapper("example.glade",events_cb)

setFontParams(ui.opand,32,"bold")
ui.window1.show_all()

gtk.main()



