[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

elif pressed == '?':
self.help()


def onHist(self):


show recent calcs log popup


from tkinter.scrolledtext import ScrolledText # or PP4E.Gui.Tour
new = Toplevel() # make new window
ok = Button(new, text="OK", command=new.destroy)
ok.pack(pady=1, side=BOTTOM) # pack first=clip last
text = ScrolledText(new, bg='beige') # add Text + scrollbar
text.insert('0.0', self.eval.getHist()) # get Evaluator text
text.see(END) # 3.0: scroll to end
text.pack(expand=YES, fill=BOTH)


new window goes away on ok press or enter key


new.title("PyCalc History")
new.bind("", (lambda event: new.destroy()))
ok.focus_set() # make new window modal:
new.grab_set() # get keyboard focus, grab app
new.wait_window() # don't return till new.destroy


def help(self):
self.infobox('PyCalc', 'PyCalc 3.0+\n'
'A Python/tkinter calculator\n'
'Programming Python 4E\n'
'May, 2010\n'
'(3.0 2005, 2.0 1999, 1.0 1996)\n\n'
'Use mouse or keyboard to\n'
'input numbers and operators,\n'
'or type code in cmd popup')


################################################################################


the expression evaluator class


embedded in and used by a CalcGui instance, to perform calculations


################################################################################


class Evaluator:
def init(self):
self.names = {} # a names-space for my vars
self.opnd, self.optr = [], [] # two empty stacks
self.hist = [] # my prev calcs history log
self.runstring("from math import ") # preimport math modules
self.runstring("from random import
") # into calc's namespace


def clear(self):
self.opnd, self.optr = [], [] # leave names intact
if len(self.hist) > 64: # don't let hist get too big
self.hist = ['clear']
else:
self.hist.append('--clear--')


def popOpnd(self):
value = self.opnd[-1] # pop/return top|last opnd
self.opnd[-1:] = [] # to display and shift next


PyCalc: A Calculator Program/Object | 1473
Free download pdf