written in Python, it is both easily customized and widely portable across window
platforms. And because it is implemented with classes, it is both a standalone program
and a reusable object library.
A Simple Calculator GUI
Before I show you how to write a full-blown calculator, though, the module shown in
Example 19-17 starts this discussion in simpler terms. It implements a limited calcu-
lator GUI, whose buttons just add text to the input field at the top in order to compose
a Python expression string. Fetching and running the string all at once produces results.
Figure 19-2 shows the window this module makes when run as a top-level script.
Example 19-17. PP4E\Lang\Calculator\calc0.py
"a simplistic calculator GUI: expressions run all at once with eval/exec"
from tkinter import *
from PP4E.Gui.Tools.widgets import frame, button, entry
class CalcGui(Frame):
def __init__(self, parent=None): # an extended frame
Frame.__init__(self, parent) # on default top-level
self.pack(expand=YES, fill=BOTH) # all parts expandable
self.master.title('Python Calculator 0.1') # 6 frames plus entry
self.master.iconname("pcalc1")
self.names = {} # namespace for variables
text = StringVar()
entry(self, TOP, text)
rows = ["abcd", "0123", "4567", "89()"]
for row in rows:
frm = frame(self, TOP)
for char in row:
button(frm, LEFT, char,
lambda char=char: text.set(text.get() + char))
frm = frame(self, TOP)
for char in "+-*/=":
button(frm, LEFT, char,
lambda char=char: text.set(text.get()+ ' ' + char + ' '))
frm = frame(self, BOTTOM)
button(frm, LEFT, 'eval', lambda: self.eval(text) )
button(frm, LEFT, 'clear', lambda: text.set('') )
def eval(self, text):
try:
text.set(str(eval(text.get(), self.names, self.names))) # was 'x'
except SyntaxError:
try:
exec(text.get(), self.names, self.names)
except:
1458 | Chapter 19: Text and Language
Do
wnload from Wow! eBook <www.wowebook.com>