Monday, January 21, 2008

Simple Application

This is just another simple example of how to program using wxPython.


#!/usr/bin/env python

import random
import wx
import string

class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,wx.ID_ANY,'Multiply Tester',size=(300,100))
panel = wx.Panel(self,wx.ID_ANY)
self.randans()
self.question = wx.StaticText(panel,wx.ID_ANY,"%d x %d = " % (self.num1,self.num2))
self.answer = wx.TextCtrl(panel,wx.ID_ANY)
button = wx.Button(panel,wx.ID_OK)
button.Bind(wx.EVT_BUTTON,self.doanswer)
self.Bind(wx.EVT_UPDATE_UI,self.Update)

sizer=wx.BoxSizer()
sizer.Add(self.question)
sizer.Add(self.answer)

luar=wx.BoxSizer(wx.VERTICAL)
luar.Add(sizer)
luar.Add(button)
panel.SetSizer(luar)

def doanswer(self,event):
calc=self.num1*self.num2
if string.atoi(self.answer.Value)==calc:
dtext="You are completely right"
else:
dtext="Wrong. The answer is %d" % (calc)
dansw=wx.MessageDialog(None,dtext,'The answer is',wx.ID_OK)
dansw.ShowModal()
self.randans()

def randans(self):
self.num1 = random.randrange(0,99)
self.num2 = random.randrange(0,10)

def Update(self,event):
self.question.SetLabel("%d x %d = " % (self.num1, self.num2))


class MApp(wx.App):

def OnInit(self):
frame=Frame()
frame.Show()
return True

if __name__ == '__main__':
app = MApp()
app.MainLoop()


It will ask you to multiply two completely random number and say whether you guessed it right or wrong.

0 comments: