|
|
"Linux Gazette...making Linux just a little more fun!"
Rapid application development using PyGTKBy Krishnakumar R.
In a competitive world, there is a definite edge to developing applications as rapidly as possible. This can be done using PyGTK which combines the robustness of Python and the raw power of GTK. This article is a hands on tutorial on building a scientific calculator using pygtk. 1. What is PyGTK ?Well, let me quote from the PyGTK source distribution:
"This archive contains modules that allow you to use gtk in Python
programs. At present, it is a fairly complete set of bindings.
Despite the low version number, this piece of software is quite
useful, and is usable to write moderately complex programs."
- README, pygtk-0.6.4
2. What are we going to do ?We are going to build a small scientific calculator using pygtk. I will explain each stage, in detail. Going through each step of this process will help one to get acquainted with pygtk. I have also put a link to the complete source code at the end of the article. 3. Packages and Basic knowledge you should have
4. Let us startThe tutorial has been divided into three stages. The code and the corresponding output are given with each stage. 5. Stage 1 - Building a WindowFirst we need to create a window. Window is actually a container. The buttons tables etc. would come within this window.
Open a new file
from gtk import *
win = GtkWindow()
def main():
win.set_usize(300, 350)
win.connect("destroy", mainquit)
win.set_title("Scientific Calculator")
win.show()
mainloop()
main()
First line is for importing the methods from the module named gtk. That means we can now use the functions present in the gtk library. Then we make an object of type GtkWindow and name it as win. After that we set the size of the window. The first argument is the breadth and the second argument is the height. We also set the title of our window. Then we call the method by name show. This method will be present in case of all objects. After setting the parameters of a particular object, we should always call show. Only when we call the show of a particular object does it becomes visible to the user. Remember that although you may create an object logically; until you call show of that object, the object will not be physically visible.
We connect the signal delete of the window to a function mainquit. The mainquit is an internal function of the gtk by calling which the presently running application can be closed. Do not worry about signals. For now just understand that whenever we delete the window (may be by clicking the cross mark at the window top), the mainquit will be called. That is, when we delete the window, the application is also quit. mainloop() is also an internal function of the gtk library. When we call the mainloop, the launched application waits in a loop for some event to occur. Here the window appears on the screen and just waits. It is waiting in the 'mainloop', for our actions. Only when we delete the window does the application come out of the loop. Save the file. Quit the editor and come to the shell prompt. At the prompt type :
Remember, you should be in Xwindow to view the output. A screen shot of output is shown below.
6. Stage 2 - Building the table and buttonsLet us start writing the second file,
from gtk import *
rows=9
cols=4
win = GtkWindow()
box = GtkVBox()
table = GtkTable(rows, cols, FALSE)
text = GtkText()
close = GtkButton("close")
button_strings=['hypot(','e',',','clear','log(','log10(','pow(','pi','sinh(','cosh(','tanh(','sqrt(','asin(',
'acos(','atan(','(','sin(','cos(','tan(',')','7','8','9','/','4','5','6','*','1','2','3','-', '0','.','=','+'
]
button = map(lambda i:GtkButton(button_strings[i]), range(rows*cols))
def main():
win.set_usize(300, 350)
win.connect("destroy", mainquit)
win.set_title("Scientific Calculator")
win.add(box)
box.show()
text.set_editable(FALSE)
text.set_usize(300,1)
text.show()
text.insert_defaults(" ")
box.pack_start(text)
table.set_row_spacings(5)
table.set_col_spacings(5)
table.set_border_width(0)
box.pack_start(table)
table.show()
for i in range(rows*cols) :
y,x = divmod(i, cols)
table.attach(button[i], x,x+1, y,y+1)
button[i].show()
close.show()
box.pack_start(close)
win.show()
mainloop()
main()
The variables The array , We insert a box into the window. To this box we insert the table. And in to this table we insert the buttons.
Corresponding Use of After the text box we insert the table in to the box. Setting the attributes of the table is trivial. The for loop inserts 4 buttons into 9 rows. The statement Finally we insert the close button to the box. Remember, Save the file and type
A screen shot of the output is given below.
7. Stage 3 - Building the backend for the calculatorSome functions are to be written to make the application do the work of calculator. This functions have been termed as the backend. These are the lines that are to be typed in to
from gtk import *
from math import *
toeval=' '
rows=9
cols=4
win = GtkWindow()
box = GtkVBox()
table = GtkTable(rows, cols, FALSE)
text = GtkText()
close = GtkButton("close")
button_strings=['hypot(','e',',','clear','log(','log10(','pow(','pi','sinh(','cosh(','tanh(','sqrt(','asin(','acos(','atan(','(','sin(','cos(','tan(',')','7','8','9','/','4','5','6','*','1','2','3','-', '0','.','=','+']
button = map(lambda i:GtkButton(button_strings[i]), range(rows*cols))
def myeval(*args):
global toeval
try :
b=str(eval(toeval))
except:
b= "error"
toeval=''
else : toeval=b
text.backward_delete(text.get_point())
text.insert_defaults(b)
def mydel(*args):
global toeval
text.backward_delete(text.get_point())
toeval=''
def calcclose(*args):
global toeval
myeval()
win.destroy()
def print_string(args,i):
global toeval
text.backward_delete(text.get_point())
text.backward_delete(len(toeval))
toeval=toeval+button_strings[i]
text.insert_defaults(toeval)
def main():
win.set_usize(300, 350)
win.connect("destroy", mainquit)
win.set_title("Scientific Calculator: scical (C) 2002 Krishnakumar.R, Share Under GPL.")
win.add(box)
box.show()
text.set_editable(FALSE)
text.set_usize(300,1)
text.show()
text.insert_defaults(" ")
box.pack_start(text)
table.set_row_spacings(5)
table.set_col_spacings(5)
table.set_border_width(0)
box.pack_start(table)
table.show()
for i in range(rows*cols) :
if i==(rows*cols-2) : button[i].connect("clicked",myeval)
elif (i==(cols-1)) : button[i].connect("clicked",mydel)
else : button[i].connect("clicked",print_string,i)
y,x = divmod(i, 4)
table.attach(button[i], x,x+1, y,y+1)
button[i].show()
close.show()
close.connect("clicked",calcclose)
box.pack_start(close)
win.show()
mainloop()
main()
A new variable Pressing any button (using a mouse) other than the If we press the Thus we have the complete scientific calculator ready. Just type
A snapshot of final application is given below.
The source code of the stages can be downloaded by clicking at the links below.
They have all .txt extension. Remove this extension and run the programs. For example change stage1.py.txt to stage1.py before executing.
Lot of example programs will be given in the examples directory, which come along with the pygtk package. In Linux, RehHat 6.2 you can find it under /usr/doc/pygtk-0.6.4/examples/ directory. Run those programs and read their source code. This will give you ample help on developing complex applications.
Happy Programming. Good Bye !
|

Krishnakumar R.