2025-12-22_python-tk-calc-app.html
001|
002|
003|
004|
005| from os import path
006| import json
007|
008| class Configuration:
009| """Application Configuration class.
009|
009| Loads and saves application configuration parameters from a JSON
009| file. Ensures reasonable defaults even if JSON file doesn't exist
009| or does exist but without required parameters.
009|
009| Attributes:
009| filename name of configuration file
009| cfg dictionary of configuration parameters
009|
009| Properties:
009| window the "window" dictionary section
009| options the "options" dictionary section
009|
009| Methods:
009| save save the configuration to its JSON file
009| """
010|
011| def __init__ (self, filename='tk_calc.json'):
012| '''New Configuration instance.'''
013| self.filename = filename
014| self.cfg = {}
015|
016|
017| if path.exists(self.filename) and path.isfile(self.filename):
018| fp = open(self.filename, mode='r', encoding='utf-8')
019| try:
020| self.cfg = json.load(fp)
021| except:
022| raise
023| finally:
024| fp.close()
025|
026|
027| if 'version' not in self.cfg:
028| self.cfg['version'] = 1
029|
030| if 'window' not in self.cfg:
031| self.cfg['window'] = {}
032|
033| if 'x' not in self.cfg['window']:
034| self.cfg['window']['x'] = 200
035| if 'y' not in self.cfg['window']:
036| self.cfg['window']['y'] = 100
037| if 'w' not in self.cfg['window']:
038| self.cfg['window']['w'] = 460
039| if 'h' not in self.cfg['window']:
040| self.cfg['window']['h'] = 240
041| if 'min.w' not in self.cfg['window']:
042| self.cfg['window']['min.w'] = 220
043| if 'min.h' not in self.cfg['window']:
044| self.cfg['window']['min.h'] = 100
045|
046| if 'options' not in self.cfg:
047| self.cfg['options'] = {}
048|
049| if 'result.font' not in self.cfg['options']:
050| self.cfg['options']['result.font'] = ["Arial",14,"bold" ]
051| if 'source.font' not in self.cfg['options']:
052| self.cfg['options']['source.font'] = ["Courier New",13]
053|
054| def __repr__ (self):
055| '''Debug string.'''
056| return f'<{type(self).__name__} @{id(self):012x}>'
057|
058| @property
059| def window (self): return self.cfg['window']
060|
061| @property
062| def options (self): return self.cfg['options']
063|
064| def save (self):
065| '''Save the current configuration.'''
066| fp = open(self.filename, mode='w', encoding='utf-8')
067| try:
068| json.dump(self.cfg, fp, indent=4, separators=(',', ':'))
069| except:
070| raise
071| finally:
072| fp.close()
073|
074|
075| from calc_wdw import Configuration
076|
077| if __name__ == '__main__':
078| print()
079| cfg = Configuration()
080| print(cfg)
081| print(cfg.window)
082| print()
083|
084|
085| from os import path
086| import tkinter as tk
087| import tkinter.ttk as ttk
088| import tkinter.messagebox as msgbox
089| import tkinter.filedialog as dialog
090| from tkinter.scrolledtext import ScrolledText
091| from calc import Calculator
092| from calc_wdw import Configuration
093|
094|
095| KEYPRESS_SHIFT = 0x00001
096| KEYPRESS_CTRL = 0x00004
097| KEYPRESS_ALT = 0x20000
098| KEYPRESS_EXT = 0x40000
099|
100| AboutText = '''\
100| Tk Calculator.
100|
100| A little demo of Python's Tk suite
100| for making windows apps. (As well
100| as being a demo of a script-driven
100| pre-fix math calculator.)
100|
100| © Wyrd Smythe December 2025
100| '''
101|
102| class Application:
103| """Tk Calculator Application class."""
104|
105| def __init__ (self, file='', mode='calc'):
106| '''New Application instance.'''
107| self.filename = file
108| self.mode = mode
109| self.dirty = False
110| self.nofile = True
111|
112|
113| self.config = Configuration()
114|
115|
116| if self.mode == 'wc':
117| self.calc = WordCounter()
118| else:
119| self.calc = Calculator()
120|
121|
122| self._create_widgets()
123| self._create_menubar()
124|
125|
126| self.root.deiconify()
127|
128|
129| if self.filename:
130| self.open_source_file()
131|
132|
133| self.update_title()
134| self.update_status(f'Mode: {self.mode}', '#7fffaf')
135| self.source.focus()
136|
137| def app_exit (self, *args):
138| '''Destroy application window.'''
139| if self.dirty:
140| ansr = msgbox.askyesno('Text is not saved.', 'Save first?')
141| if ansr:
142| self.file_save()
143| return
144|
145|
146| geom = self.root.wm_geometry()
147| dims,xpos,ypos = geom.split('+')
148| xdim,ydim = dims.split('x')
149| self.config.window['x'] = int(xpos)
150| self.config.window['y'] = int(ypos)
151| self.config.window['w'] = int(xdim)
152| self.config.window['h'] = int(ydim)
153| self.config.options['lastfile'] = self.filename
154|
155|
156| self.config.save()
157|
158|
159| self.root.destroy()
160|
161| def calculate (self, *args):
162| '''Execute the script.'''
163| self.update_status('Calculating...', '#7f7f7f')
164| self.calc.reset()
165|
166|
167| text = self.source.get('1.0','end')
168| if not text:
169| msgbox.showwarning('No text.', 'Nothing to calculate.')
170| return
171|
172| try:
173|
174| tokens = self.calc.parse_text(text)
175|
176|
177| answer = self.calc.execute(tokens)
178|
179| except Exception as e:
180| self.result.set('#ERROR#')
181| self.update_status(e, '#ff3322')
182| else:
183| self.result.set(answer)
184| self.update_status('Done.')
185|
186| def open_source_file (self):
187| '''Open and load a source code text file into the Textbox.'''
188|
189| fp = open(self.filename, mode='r', encoding='utf8')
190| try:
191| text = fp.read()
192| except Exception as e:
193| self.update_status(e, '#ff3322')
194| finally:
195| fp.close()
196|
197|
198| self.load_source_file(text)
199|
200| def load_source_file (self, text):
201| '''Load a source code text file into the Textbox.'''
202|
203| self.calc.reset()
204| self.result.set('')
205| self.dirty = False
206| self.nofile = False
207|
208| self.source.delete('1.0', 'end')
209| self.source.insert('1.0', text)
210| self.source.edit_modified(0)
211|
212| self.update_title()
213| self.update_status(f'opened: {self.filename} ({len(text)} chars)')
214|
215| def save_source_file (self):
216| '''Save the Textbox text to a text file.'''
217| text = self.source.get('1.0','end')
218| self.source.edit_modified(0)
219| if not text:
220| msgbox.showwarning('No text.', 'Nothing to save.')
221| return
222| fp = open(self.filename, mode='w', encoding='utf8')
223| try:
224| fp.write(text)
225| except Exception as e:
226| self.update_status(e, '#ff3322')
227| finally:
228| fp.close()
229| self.dirty = False
230| self.update_title()
231| self.update_status(f'saved: {self.filename} ({len(text)} chars)')
232|
233| def update_title (self):
234| '''Update the window title (with new filename).'''
235| name = f'[{path.basename(self.filename)}]' if self.filename else ''
236| flag = '***' if self.dirty else ''
237| self.root.title(f'Tk Calculator {name}{flag}')
238|
239| def update_status (self, message, color='#ffffff'):
240| '''Write to the result.'''
241| self.status['text'] = message
242| self.status['foreground'] = color
243|
244| def file_new (self):
245| '''Menu: File/New. Reset everything.'''
246| if self.dirty:
247| ansr = msgbox.askyesno('Text is not saved.', 'Save first?')
248| if ansr:
249| self.file_save()
250| return
251|
252| self.calc.reset()
253| self.result.set('')
254| self.source.delete('1.0', 'end')
255| self.source.edit_modified(0)
256| self.dirty = False
257| self.nofile = True
258| self.filename = ''
259| self.update_title()
260| self.update_status('(new)')
261|
262| def file_open (self):
263| '''Menu: File/Open.'''
264| if self.dirty:
265| ansr = msgbox.askyesno('Text is not saved.', 'Save first?')
266| if ansr:
267| self.file_save()
268| return
269| props = dict(
270| parent=self.root,
271| title="Select an input file:",
272| filetypes=[('Text files','*.txt'),('All files','*')],
273| defaultextension='txt',
274| initialdir=path.dirname(self.filename),
275| initialfile=path.basename(self.filename),
276| mode='r',
277| )
278| fileobj = dialog.askopenfile(**props)
279| if fileobj:
280|
281| self.filename = fileobj.name
282|
283| self.load_source_file(fileobj.read())
284|
285| def file_save (self):
286| '''Menu: File/Save.'''
287| if self.nofile:
288| self.file_save_as()
289| return
290| self.save_source_file()
291|
292| def file_save_as (self):
293| '''Menu: File/Save As...'''
294| props = dict(
295| parent=self.root,
296| title="Enter a save-as filename:",
297| filetypes=[('Text files','*.txt'),('All files','*')],
298| defaultextension='txt',
299| initialdir=path.dirname(self.filename),
300| initialfile=path.basename(self.filename),
301| confirmoverwrite=1,
302| )
303| name = dialog.asksaveasfilename(**props)
304| if 0 < len(name):
305| self.filename = name
306| self.nofile = False
307| self.save_source_file()
308|
309| def copy_source (self):
310| '''Menu: Edit/Copy Source.'''
311| txt = self.source.get('1.0','end').strip()
312| if not txt:
313| msgbox.showwarning('No source text!','Nothing to copy!')
314| return
315| self.root.clipboard_clear()
316| self.root.clipboard_append(txt)
317| self.update_status('Copied source text to clipboard.')
318|
319| def copy_result (self):
320| '''Menu: Edit/Copy Result.'''
321| txt = self.result.get()
322| if not txt:
323| msgbox.showwarning('No result text!','Nothing to copy!')
324| return
325| self.root.clipboard_clear()
326| self.root.clipboard_append(txt)
327| self.update_status('Copied result text to clipboard.')
328|
329| def view_results (self):
330| '''Menu: View/Results.'''
331| lines = [str(res) for res in self.calc.results]
332| msgbox.showinfo('All Results', '\n'.join(lines))
333|
334| def view_variables (self):
335| '''Menu: View/Variables.'''
336| lines = [f'{n} = {v}' for n,v in self.calc.variables.items()]
337| msgbox.showinfo('Variables', '\n'.join(lines))
338|
339| def view_operators (self):
340| '''Menu: View/Operators.'''
341| names = list(sorted(self.calc.opnames()))
342| text = ', '.join(names)
343| msgbox.showinfo('Operators', f'{text} ({len(names)})')
344|
345| def about (self):
346| '''About this Application.'''
347| msgbox.showinfo('About', AboutText)
348|
349| def txt_keypress (self, evt):
350| '''Textbox key handler.'''
351| if self.source.edit_modified():
352| if not self.dirty:
353| self.dirty = True
354| self.update_title()
355|
356| def app_keypress (self, evt):
357| '''Application key handler.'''
358|
359| if evt.state & KEYPRESS_ALT:
360| if evt.keysym in ['C','c']:
361| self.copy_source()
362| return
363| if evt.keysym in ['R','r']:
364| self.copy_result()
365| return
366| if evt.keysym in ['S','s']:
367| self.file_save_as()
368| return
369| if evt.keysym in ['X','x']:
370| self.app_exit('Alt-X')
371| return
372| return
373|
374| if evt.state & KEYPRESS_CTRL:
375| if evt.keysym in ['N','n']:
376| self.file_new()
377| return
378| if evt.keysym in ['O','o']:
379| self.file_open()
380| return
381| if evt.keysym in ['S','s']:
382| self.file_save()
383| return
384| return
385|
386| if evt.keysym == 'F1':
387| self.view_results()
388| return
389| if evt.keysym == 'F2':
390| self.view_variables()
391| return
392| if evt.keysym == 'F4':
393| self.view_operators()
394| return
395| if evt.keysym == 'F12':
396| self.about()
397| return
398|
399| def _create_widgets (self):
400| '''Create and place the window widgets.'''
401|
402|
403| self.root = tk.Tk()
404| self.root.withdraw()
405|
406|
407| xpos = self.config.window['x']
408| ypos = self.config.window['y']
409| xdim = self.config.window['w']
410| ydim = self.config.window['h']
411| self.root.geometry(f'{xdim}x{ydim}+{xpos}+{ypos}')
412|
413|
414| minx = self.config.window['min.w']
415| miny = self.config.window['min.h']
416| self.root.minsize(minx, miny)
417|
418|
419| self.root.bind('<Escape>', self.app_exit)
420| self.root.bind('<F5>', self.calculate)
421| self.root.bind('<KeyPress>' , self.app_keypress)
422|
423|
424| self.style = ttk.Style(self.root)
425| self.style.theme_use('clam')
426|
427|
428| self.result = tk.StringVar()
429|
430|
431| self.wndw = tk.Frame(self.root, bg='#666666', relief='solid')
432| self.head = tk.Frame(self.wndw, bg='#996633', relief='sunken')
433| self.main = tk.Frame(self.wndw, bg='#336699', relief='sunken')
434| self.sbar = tk.Frame(self.wndw, bg='#999999', relief='sunken')
435|
436|
437| self.label1 = tk.Button(self.head)
438| self.label1.config(text='Result:')
439| self.label1.config(font=('Segoe UI',12))
440| self.label1.config(justify='left')
441| self.label1.config(command=self.calculate)
442| self.label1.pack(
443| side='left', anchor='e',
444| padx=0, pady=0, ipadx=4, ipady=0
445| )
446|
447| self.style.configure('TEntry',
448| fieldbackground='#000000',
449| background='#000000', foreground='#00ff00',
450| padding=(7,0)
451| )
452| self.output = ttk.Entry(self.head)
453| self.output.config(font=('Segoe UI Variable',14,'bold'))
454| self.output.config(justify='left')
455| self.output.config(textvariable=self.result)
456| self.output.state(['readonly'])
457| self.output.pack(
458| side='right', anchor='w',
459| fill='both', expand=True, padx=0, pady=0
460| )
461|
462|
463| self.source = ScrolledText(self.main)
464| self.source.config(wrap=tk.WORD, tabs='30p')
465| self.source.config(font=('Lucida Sans Typewriter',13))
466| self.source.bind('<KeyPress>', self.txt_keypress)
467| self.source.pack(side='top', fill='both', expand=True)
468|
469|
470| self.status = tk.Label(self.sbar)
471| self.status.config(background='#000000')
472| self.status.config(foreground='#ffffff')
473| self.status.config(relief='flat')
474| self.status.config(font=('Segoe UI Variable',9))
475| self.status.config(anchor='w')
476| self.status.pack(side='left', fill='x', expand=True, ipadx=4)
477|
478| self.copyright = tk.Label(self.sbar)
479| self.copyright.config(text="© 2025")
480| self.copyright.config(background='#000000')
481| self.copyright.config(foreground='#66ccff')
482| self.copyright.config(relief='flat')
483| self.copyright.config(font=('Segoe UI Variable',9))
484| self.copyright.config(justify='center')
485| self.copyright.pack(side='right', ipadx=4)
486|
487|
488| self.wndw.pack(side='top', fill='both',expand=True, padx=5,pady=5)
489| self.sbar.pack(side='bottom', fill='x', padx=1,pady=1)
490| self.head.pack(side='top', fill='x')
491| self.main.pack(side='top', fill='both',expand=True)
492|
493| def _create_menubar (self):
494| '''Create the menubar.'''
495|
496| self.mbar = tk.Menu(self.root)
497|
498| kw = lambda t,u,a,c: dict(
499| label=t, underline=u, accelerator=a, command=c
500| )
501|
502| self.mbarFile = tk.Menu(self.mbar, name='fileMenu', tearoff=0)
503| self.mbarFile.add_command(**kw('New' ,0,'Ctrl+N',self.file_new))
504| self.mbarFile.add_command(**kw('Open...' ,0,'Ctrl+O',self.file_open))
505| self.mbarFile.add_command(**kw('Save' ,0,'Ctrl+S',self.file_save))
506| self.mbarFile.add_command(**kw('Save As...',5,'Alt+S' ,self.file_save_as))
507| self.mbarFile.add_separator()
508| self.mbarFile.add_command(**kw('Exit', 1, 'Alt+X', self.app_exit))
509|
510|
511| self.mbarEdit = tk.Menu(self.mbar, name='editMenu', tearoff=0)
512| self.mbarEdit.add_command(**kw('Copy Result',0,'Alt+R',self.copy_result))
513| self.mbarEdit.add_command(**kw('Copy Source',5,'Alt+C',self.copy_source))
514|
515|
516| self.mbarView = tk.Menu(self.mbar, name='viewMenu', tearoff=0)
517| self.mbarView.add_command(**kw('All Results',0,'F1',self.view_results))
518| self.mbarView.add_command(**kw('Variables' ,0,'F2',self.view_variables))
519| self.mbarView.add_separator()
520| self.mbarView.add_command(**kw('Operators' ,0,'F4',self.view_operators))
521| self.mbarView.add_separator()
522| self.mbarView.add_command(**kw('About', 0, 'F12', self.about))
523|
524|
525| self.mbar.add_cascade(label='File', menu=self.mbarFile, underline=0)
526| self.mbar.add_cascade(label='Edit', menu=self.mbarEdit, underline=0)
527| self.mbar.add_cascade(label='View', menu=self.mbarView, underline=0)
528|
529|
530| self.root['menu'] = self.mbar
531|
532|
533| from calc_wdw import Application
534|
535| if __name__ == '__main__':
536| print()
537| app = Application()
538| app.root.mainloop()
539| print()
540|
541|
542|
543|
544|
545|
546| class Token:
547| """Token class."""
548| Constant = 1
549| NamedVal = 2
550| Operator = 3
551|
552| TTNames = ['', 'Cons', 'Name', 'Oper']
553|
554| def __init__ (self, token_type, token_value):
555| '''New instance.'''
556| self._t = token_type
557| self._v = token_value
558|
559| @property
560| def ttype (self): return self._t
561|
562| @property
563| def value (self): return self._v
564|
565| def __repr__ (self):
566| '''Debug string.'''
567| tt = type(self).TTNames[self._t]
568| return f'<{typename(self)} {tt} @{id(self):012x}>'
569|
570| def __str__ (self):
571| '''String version.'''
572| tt = type(self).TTNames[self._t]
573| return f'{tt}: {self._v}'
574|
575|
576| class DatumToken (Token):
577| def __init__ (self, token_value):
578| '''New instance.'''
579| super().__init__(Token.Constant, token_value)
580|
581| class NamedValToken (Token):
582| def __init__ (self, token_value):
583| '''New instance.'''
584| super().__init__(Token.NamedVal, token_value)
585|
586| class OperatorToken (Token):
587| def __init__ (self, token_value):
588| '''New instance.'''
589| super().__init__(Token.Operator, token_value)
590|
591|
592| import time
593| import math
594| import random
595| from calc import Token, DatumToken,NamedValToken,OperatorToken
596|
597| class Calculator:
598| """Prefix Calculator class."""
599|
600|
601| SkipNames = [
602| "opnames", "isoperator", "datum", "reset", "execute",
603| 'tokens', 'variables', 'constants', 'result',
604| "SkipNames"
605| ]
606|
607| def __init__ (self, tokens=None, variables=None):
608| '''New instance.'''
609| self.tokens = [] if tokens is None else list(tokens)
610| self.variables = {} if variables is None else variables
611| self.constants = {
612| 'e':math.e, 'pi':math.pi, 'tau':math.tau,
613| 'PL':1.61625e-35,
614| 'h':6.62607015e-34, 'hbar':1.054571817e-34,
615| 'c':299_792_458, 'c2':89_875_517_873_681_764,
616| 'LY':9_460_730_472_580_800,
617| }
618| self.results = []
619|
620| def __repr__ (self):
621| '''Debug string.'''
622| return f'<{type(self).__name__} @{id(self):012x}>'
623|
624| def __str__ (self):
625| '''String version.'''
626| return ' '.join(self.tokens)
627|
628| @classmethod
629| def opnames (cls):
630| '''Return a list of operator names.'''
631| return list(filter(cls.isoperator, cls.__dict__))
632|
633| @classmethod
634| def isoperator (cls, name):
635| '''Return True if name is a valid operator name.'''
636|
637|
638| if name.startswith('_'):
639| return False
640|
641| if name.startswith('parse'):
642| return False
643|
644| if name in cls.SkipNames:
645| return False
646|
647|
648| return hasattr(cls, name)
649|
650| @classmethod
651| def datum (cls, word):
652| '''Determine and return appropriate token type.'''
653|
654|
655| if cls.isoperator(word):
656| return OperatorToken(word)
657|
658|
659| try:
660| return DatumToken(int(word, base=0))
661| except:
662| pass
663|
664|
665| try:
666| return DatumToken(float(word))
667| except:
668| pass
669|
670|
671|
672| return NamedValToken(word)
673|
674| @classmethod
675| def parse_words (cls, words):
676| return [Calculator.datum(word) for word in words]
677|
678| @classmethod
679| def parse_text (cls, text):
680| words = text.split()
681| return cls.parse_words(words)
682|
683| def reset (self):
684| '''Reset.'''
685| self.variables = {}
686| self.results = []
687|
688| def execute (self, tokens=None):
689| '''Execute the list of tokens as a formula.'''
690| if tokens is not None:
691| self.tokens = tokens
692|
693|
694| self.reset()
695|
696|
697| if not self.tokens:
698| self.results = ['<null>']
699| return
700|
701|
702| while len(self.tokens):
703|
704| value = self._get_value()
705|
706| self.results.append(value)
707|
708|
709| return self.results[-1]
710|
711| def _get_value (self):
712| '''Get next value; evaluates operators.'''
713| if len(self.tokens) == 0:
714| raise RuntimeError('No tokens.')
715|
716|
717| tok = self.tokens.pop(0)
718|
719|
720| match tok.ttype:
721|
722|
723| case Token.Constant:
724| return tok.value
725|
726|
727| case Token.NamedVal:
728| if tok.value in self.constants:
729| return self.constants[tok.value]
730| if tok.value in self.variables:
731| return self.variables[tok.value]
732| raise ValueError(f'Uknown name: "{tok.value}"')
733|
734|
735| case Token.Operator:
736|
737| if not hasattr(self, tok.value):
738| raise ValueError(f'Unknown operator: {tok}')
739| oper = getattr(self, tok.value)
740| return oper()
741|
742|
743| case _:
744| raise RuntimeError(f'Unknown Token Type: {tok}.')
745|
746| def set (self):
747| '''Set a variable's value.'''
748|
749|
750| tok = self.tokens.pop(0)
751| if not isinstance(tok,NamedValToken):
752| SyntaxError(f'Variable name required, not {tok.value}.')
753|
754|
755| value = self._get_value()
756| self.variables[tok.value] = value
757|
758|
759| return value
760|
761| def now (self):
762| return time.time()
763|
764| def randnum (self):
765| return random.random()
766|
767| ...
768| ...
769|
770| def add (self):
771| a = self._get_value()
772| b = self._get_value()
773| return (a + b)
774|
775| plus = add
776|
777| def subtract (self):
778| a = self._get_value()
779| b = self._get_value()
780| return (a - b)
781|
782| sub = subtract
783|
784| ...
785| ...
786|
787| def square (self):
788| x = self._get_value()
789| return pow(x, 2)
790|
791| sqr = square
792|
793| def squareroot (self):
794| x = self._get_value()
795| return math.sqrt(x)
796|
797| sqrt = squareroot
798|
799| def log (self):
800| x = self._get_value()
801| b = self._get_value()
802| return math.log(x, b)
803|
804| def log10 (self):
805| x = self._get_value()
806| return math.log10(x)
807|
808| def log2 (self):
809| x = self._get_value()
810| return math.log2(x)
811|
812| ...
813| ...
814|
815| def hypot2 (self):
816| x = self._get_value()
817| y = self._get_value()
818| return math.hypot(x, y)
819|
820| def hypot3 (self):
821| x = self._get_value()
822| y = self._get_value()
823| z = self._get_value()
824| return math.hypot(x, y, z)
825|
826| ...
827| ...
828|
829| def sum (self):
830| n = self._get_value()
831| total = 0
832| for _ in range(n):
833| total += self._get_value()
834| return total
835|
836| def min (self):
837| n = self._get_value()
838| minimum = None
839| for _ in range(n):
840| value = self._get_value()
841| if (minimum is None) or (value < minimum):
842| minimum = value
843| return minimum
844|
845| ...
846| ...
847|
848|
849| from calc import Calculator
850|
851| if __name__ == '__main__':
852| print()
853| g = Calculator.opnames()
854| print(f'{len(g)} items:')
855| print(g)
856| print()
857|
858|
859| from calc import Calculator
860|
861| formula = """\
861| set x rads 45
861| set y rads 45
861|
861| sqrt
861| add
861| sqr cos x
861| sqr sin y
861| """
862|
863| if __name__ == '__main__':
864| print()
865|
866|
867| tokens = Calculator.parse_text(formula)
868|
869|
870| for token in tokens:
871| print(token)
872| print()
873|
874|
875| from calc import DatumToken, OperatorToken
876| from calc import Calculator
877|
878| formula = [
879| OperatorToken('add'),
880| DatumToken(21),
881| DatumToken(42),
882| ]
883|
884| if __name__ == '__main__':
885|
886| calc = Calculator(formula)
887| result = calc.execute()
888| print()
889| print(f'{result = }')
890| print()
891|
892|
893| from calc import DatumToken, NamedValToken, OperatorToken
894| from calc import Calculator
895|
896| formula = [
897| OperatorToken('set'),
898| NamedValToken('x'),
899| OperatorToken('rads'),
900| DatumToken(45),
901| OperatorToken('set'),
902| NamedValToken('y'),
903| OperatorToken('rads'),
904| DatumToken(45),
905| OperatorToken('squareroot'),
906| OperatorToken('add'),
907| OperatorToken('sqr'),
908| OperatorToken('cos'),
909| NamedValToken('x'),
910| OperatorToken('sqr'),
911| OperatorToken('sin'),
912| NamedValToken('y'),
913| ]
914|
915| if __name__ == '__main__':
916| print()
917|
918|
919| for tok in formula:
920| print(tok)
921| print()
922|
923|
924| calc = Calculator(formula)
925| result = calc.execute()
926| print()
927| print(f'{result = }')
928| print()
929| print(f'calc-result: {calc.results}')
930|
931|
932| from calc import Calculator
933|
934| formula = """\
934| set x rads 45
934| set y rads 45
934|
934| sqrt
934| add
934| sqr cos x
934| sqr sin y
934| """
935|
936| if __name__ == '__main__':
937| print()
938|
939|
940| tokens = Calculator.parse_text(formula)
941|
942|
943| for token in tokens:
944| print(token)
945| print()
946|
947|
948| calc = Calculator(tokens)
949| result = calc.execute()
950| print()
951| print(f'{result = }')
952| print()
953| print(f'calc-result: {calc.results}')
954| print()
955|
956|
957| from calc_wdw import Application
958|
959| if __name__ == '__main__':
960| print()
961| try:
962| app = Application(mode='calc')
963| app.root.mainloop()
964|
965| except Exception as e:
966| print(f'Oops! {e}')
967|
968| else:
969| print('Success!')
970|
971| finally:
972| print('Done.')
973|
974| print()
975|
976|
977| class Application:
978| """Tk Calculator Application class."""
979|
980| def __init__ (self, file='', mode='calc'):
981| '''New Application instance.'''
982| self.filename = file
983| self.mode = mode
984| self.dirty = False
985| self.nofile = True
986|
987|
988| self.config = Configuration()
989|
990|
991| if self.mode == 'wc':
992| self.calc = WordCounter()
993| else:
994| self.calc = Calculator()
995|
996|
997| self._create_widgets()
998| self._create_menubar()
999|
1000| self.root.deiconify()
1001|
1002| if self.filename:
1003| self.open_source_file()
1004|
1005| self.update_title()
1006| self.update_status(f'Mode: {self.mode}', '#7fffaf')
1007| self.source.focus()
1008|
1009| ...
1010| ...
1011| ...
1012|
1013|
1014| class AlphaMap (dict):
1015| """Transation filter."""
1016|
1017| def __init__ (self, others=""):
1018| '''New AlphaMap instance.'''
1019| self[ord('.')] = '.'
1020| self[ord('_')] = '_'
1021|
1022|
1023| for cx in range(26):
1024| self[UCA+cx] = chr(UCA+cx)
1025| self[LCA+cx] = chr(LCA+cx)
1026|
1027|
1028| for cx in range(10):
1029| self[DIG0+cx] = chr(DIG0+cx)
1030|
1031|
1032| for ch in others:
1033| cx = ord(ch)
1034| assert 0 <= cx < 256, ValueError(f'Illegal character: "{ch}"')
1035| self[cx] = ch
1036|
1037| def __missing__ (self, cx):
1038| """All other characters map to spaces."""
1039| return " "
1040|
1041|
1042| class WordCounter:
1043| '''Word-Counter "Calculator".
1043|
1043| A basic word-counter to replace the Calculator class.
1043| This class replicates the attributes and methods of
1043| the Calculator class but just counts words.
1043|
1043| Attributes:
1043| tokens list of words to count
1043| variables unused but expected
1043| constants unused but expected
1043| results output string
1043|
1043| Methods:
1043| reset reset calculator
1043| execute execute tokens
1043|
1043| Class Methods:
1043| opnames returns empty list
1043| parse_text given text, return list of words
1043|
1043| '''
1044| def __init__ (self, **kwargs):
1045| '''New instance.'''
1046| self.tokens = []
1047| self.variables = {}
1048| self.constants = []
1049| self.results = ['']
1050|
1051| def __repr__ (self):
1052| '''Debug string.'''
1053| return f'<{typename(self)} @{id(self):012x}>'
1054|
1055| def __str__ (self):
1056| '''String version.'''
1057| return ' '.join(self.tokens)
1058|
1059| def reset (self):
1060| '''Reset.'''
1061| self.results = ['']
1062|
1063| def execute (self, words=''):
1064| '''Count the list of words.'''
1065| self.tokens = words
1066| self.unique = list(sorted(set(words)))
1067| self.nw = len(self.tokens)
1068| self.nu = len(self.unique)
1069| self.nc = sum(len(word) for word in self.tokens)
1070| text = f'{self.nw} words ({self.nu} unique), {self.nc} chars'
1071| self.results = [text]
1072| return text
1073|
1074| @classmethod
1075| def parse_text (cls, text):
1076| '''Break text into words. Remove all punctuation.'''
1077| txt = text.translate(AlphaMap())
1078| txt = txt.replace('. ', ' ')
1079| if txt.endswith('.'): txt = txt[:-1]
1080| txt = txt.lower()
1081| return txt.split()
1082|
1083| @classmethod
1084| def opnames (cls):
1085| '''No operators but an expected method.'''
1086| return []
1087|
1088|
1089| from examples import WordCounter
1090|
1091| Source = '''\
1091| The sqrt (square root) operator expects a single value,
1091| so it evaluates the mul operator. The mul operator
1091| expects two values, so it first processes the first add.
1091| Which expects two values and finds 2 and 5 (more correctly,
1091| it evaluates the next two terms which evaluate respectively
1091| to 2 and 5). It has its values, so it sums and returns 7,
1091| which provides the first value for the mul operator.
1091| Wanting a second value, the mul operator evaluates the
1091| second add. Which expects two values and finds 3 and the
1091| log10 operator. Which expects a value and finds 7, so it
1091| returns log10(7)≈0.845 as the second value for the add
1091| operator. Which can now sum its values and return ~3.845,
1091| providing the second value for the mul operator. Which can
1091| now do 7×~3.845=~26.915686, providing a value for the sqrt
1091| operator.
1091| '''
1092|
1093| if __name__ == '__main__':
1094| print()
1095| wc = WordCounter()
1096|
1097|
1098| words = wc.parse_text(Source)
1099|
1100|
1101| result = wc.execute(words)
1102|
1103| print(result)
1104| print()
1105| print(wc.tokens)
1106| print()
1107| print(wc.unique)
1108| print()
1109|
1110|
1111|