1
2
3 """
4 Calculadora com GUI em Tkinter, utilizando funções internas do Python
5 Baseada na implementação de Mark Lutz em "Programming Python", pág. 675
6
7 Autor deste script: Jean-Guy Schneider <schneidr@iam.unibe.ch>
8 Última modificação Mon Jun 22 17:36:02 MET DST 1998
9 """
10 from Tkinter import *
11
12 class CalcGUI (Frame):
13 """
14 class 'CalcGUI': a simple calculator
15 """
16
17 def __init__ (self, master=None):
18 Frame.__init__ (self, master)
19 self.pack (expand=YES, fill=BOTH)
20 self.master.title ('Python Calculator')
21 self.master.iconname ("pcalc")
22
23 self._names = {}
24
25 self._text = Text (self, width=16, height=1)
26 self._text.pack (expand=YES, fill=X)
27
28 rows = ["abcd", "0123", "4567", "89()"]
29 for row in rows:
30 frm = Frame (self)
31 for char in row:
32 but = Button (frm, text=char,
33 command=lambda s=self, y=char: s._append (y))
34 but.pack (side=LEFT, expand=YES, fill=X)
35 frm.pack (expand=YES, fill=X)
36
37 frm2 = Frame (self)
38 for char in "+-*/=":
39 but = Button (frm2, text=char,
40 command=lambda s=self, y=char: s._append (' '+y+' '))
41 but.pack (side=LEFT, expand=YES, fill=X)
42 frm2.pack (expand=YES, fill=X)
43
44 frm3 = Frame (self)
45 but = Button (frm3, text='eval', command=lambda s=self: s.eval ())
46 but.pack (side=LEFT, expand=YES, fill=X)
47 but = Button (frm3, text='clear', command=lambda s=self: s._clear ())
48 but.pack (side=LEFT, expand=YES, fill=X)
49 but = Button (frm3, text='exit', command=self.quit)
50 but.pack (side=LEFT, expand=YES, fill=X)
51 frm3.pack (expand=YES, fill=X)
52
53 def eval (self):
54 try:
55 cont = self._get()
56 self._clear()
57
58 self._append (`eval (cont, self._names, self._names)`)
59 except SyntaxError:
60 try:
61 exec (cont, self._names, self._names)
62 except:
63 self._append ("ERROR")
64 else:
65 self._clear()
66 except:
67 self._append ("ERROR")
68
69
70 def _clear (self):
71 """Clear text widget"""
72 self._text.delete ('1.0', '2.0')
73
74 def _append (self, text):
75 """Append 'text' to text widget"""
76 self._text.insert ('1.end', text)
77
78 def _get (self):
79 """get contents of text widget"""
80 return self._text.get ('1.0', '1.end')
81
82 if __name__ == '__main__':
83 CalcGUI().mainloop()