tk-calc.html
001| """Tk-Calc.
001|
001| TODO: More conversions. (Many more.)
001| TODO: Separate calculator modules from app.
001| TODO: Allow commas in numbers. (Output them, too?)
001| TODO: Make CALL work.
001|
001| Classes:
001| Application ~implements a Tk application
001| Calculator ~default calculator
001| DecimalCalculator ~calculator using Decimal numbers
001| WordCounter ~word counter
001|
001| Token ~script token base class
001| DatumToken (Token) ~literal value token
001| NamedValToken (Token) ~named value token (var or cons)
001| OperatorToken (Token) ~operator token
001|
001| AlphaMap (dict) ~character filter
001|
001| Functions:
001| dec_pi ~Decimal version of pi
001| dec_cos ~Decimal version cos function
001| dec_sin ~Decimal version sin function
001| expand_decimal ~expand Decimal number
001|
001| Data:
001| AboutText ~text for About msgbox
001| FileTypes ~list of filetypes for open/save dialogs
001| <name>Key ~settings file parameter names
001| Dflt<name> ~default settings parameters
001|
001| Commands:
001| main do_main ~start the Tk GUI app
001| test do_test ~test
001|
001| Function Syntax and Examples:
001|
001| FUNC <name> <expression> END
001| CALL <name> <arglist> END
001|
001| func lorentz
001| div 1 sqrt sub 1 div $1 c
001| end
001| set gamma call lorentz 0.50 end
001|
001| func hypot
001| sqrt add square $1 square $2
001| end
001| set x 3
001| set y 4
001| set length call hypot x y end
001|
001| func hypot
001| sqrt add square X square Y
001| end
001| set X 3
001| set Y 4
001| set length call hypot end
001|
001| """
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| import time
007| import math
008| import json
009| import random
010| import decimal as dec
011| import tkinter as tk
012| import tkinter.ttk as ttk
013| import tkinter.filedialog as dialog
014| import tkinter.messagebox as msgbox
015| import tkinter.simpledialog as simdia
016| from tkinter.scrolledtext import ScrolledText
017| from logger import logger,info,debug,trace, LogFilenameTimestamp
018| from goodies import typename, KWARG, makefilename, isreallyafile, plural, list2str
019| from dates import CST
020| import jconfig as jcfg
021| import tkutil as util
022|
023| BasePath = r'C:\CJS\prj\Python\app\tk'
024| CnfgPath = path.join(BasePath, 'cfg')
025| DataPath = path.join(BasePath, 'dat')
026| ListPath = path.join(BasePath, 'out')
027| Log = logger('Tk-Calc')
028|
029| CMND = 'test'
030| ARGS = {
031|
032|
033| }
034| bag = {}
035|
036|
037| class Token:
038| """Token class.
038|
038| Implements a basic type/value token. A token instance is one of
038| three types: Constant, NamedVal or Operator. In a Constant, the
038| value is a literal (numeric) value. In a NamedVal, the value is
038| the name of a Variable. In an Operator, the value is the name
038| of the operator.
038|
038| Class Attributes:
038| Constant a token type
038| NamedVal a token type
038| Operator a token type
038| TTNames list of token type strings
038|
038| Instance Attributes:
038| _t token type (internal)
038| _v token value (internal)
038|
038| Instance Properties:
038| ttype token type (use instead of _t)
038| value token value (use instead of _v)
038|
038| Methods:
038| (none)
038| """
039| Constant = 1
040| NamedVal = 2
041| Operator = 3
042| Special = 4
043|
044| TTNames = ['', 'Cons', 'Name', 'Oper', 'Spcl']
045|
046| def __init__ (self, token_type, token_value):
047| '''New instance.'''
048| self._t = token_type
049| self._v = token_value
050|
051| @property
052| def ttype (self): return self._t
053|
054| @property
055| def value (self): return self._v
056|
057| def __repr__ (self):
058| '''Debug string.'''
059| return f'<{typename(self)} {self._v} @{id(self):012x}>'
060|
061| def __str__ (self):
062| '''String version.'''
063| tt = type(self).TTNames[self._t]
064| return f'{tt}: {self._v}'
065|
066|
067| class DatumToken (Token):
068| def __init__ (self, token_value):
069| '''New instance.'''
070| super().__init__(Token.Constant, token_value)
071|
072|
073| class NamedValToken (Token):
074| def __init__ (self, token_value):
075| '''New instance.'''
076| super().__init__(Token.NamedVal, token_value)
077|
078|
079| class OperatorToken (Token):
080| def __init__ (self, token_value):
081| '''New instance.'''
082| super().__init__(Token.Operator, token_value)
083|
084|
085| class SpecialToken (Token):
086| def __init__ (self, token_value):
087| '''New instance.'''
088| super().__init__(Token.Special, token_value)
089|
090|
091|
092| class Calculator:
093| """Prefix Calculator class.
093|
093| Implements a script-based pre-fix math calculator.
093|
093| Attributes:
093| tokens list of tokens to process
093| variables dictionary of variables
093| constants dictionary of constants
093| result list of outputs
093|
093| Methods:
093| reset reset calculator
093| execute execute tokens
093| <operator> various methods implementing each operator
093| _get_value get next token value; evaluates operators
093|
093| Class Methods:
093| opnames return list of operator names
093| isoperator determines whether a name is an operator
093| datum given a word, return an appropriate token
093| parse_words given list of words, return list of tokens
093| parse_text given text, return list of tokens
093| """
094|
095| SkipNames = [
096| "opnames", "isoperator", "datum", "reset", "execute",
097| 'tokens', 'variables', 'constants', 'result',
098| "SkipNames"
099| ]
100|
101| def __init__ (self, tokens=None, variables=None, functions=None):
102| '''New instance.'''
103| self.tokens = [] if tokens is None else list(tokens)
104| self.variables = {} if variables is None else variables
105| self.functions = {} if functions is None else functions
106| self.constants = {
107| 'e':math.e, 'pi':math.pi, 'tau':math.tau,
108| 'PL':1.61625e-35,
109| 'h':6.62607015e-34, 'hbar':1.054571817e-34,
110| 'c':299_792_458, 'c2':89_875_517_873_681_764,
111| 'LY':9_460_730_472_580_800,
112| }
113| self.results = []
114| if len(self.tokens):
115| self.execute()
116|
117| def __repr__ (self):
118| '''Debug string.'''
119| return f'<{typename(self)} @{id(self):012x}>'
120|
121| def __str__ (self):
122| '''String version.'''
123| return ' '.join(self.tokens)
124|
125| def reset (self, variables=None, functions=None):
126| '''Reset.'''
127| self.variables = {} if variables is None else variables
128| self.functions = {} if functions is None else functions
129| self.results = []
130|
131| def execute (self, tokens=None):
132| '''Execute the list of tokens as a formula.'''
133| if tokens is not None:
134| self.tokens = list(tokens)
135|
136|
137| self.reset()
138|
139|
140| if not self.tokens:
141| self.results = ['<null>']
142| return
143|
144|
145| while len(self.tokens):
146|
147| value = self._get_value()
148|
149| self.results.append(value)
150|
151|
152| return self.results[-1]
153|
154| def _get_value (self):
155| '''Get next token value; evaluates operators.'''
156| if len(self.tokens) == 0:
157| raise RuntimeError('No tokens.')
158|
159|
160| tok = self.tokens.pop(0)
161|
162|
163| match tok.ttype:
164|
165|
166| case Token.Constant:
167| return tok.value
168|
169|
170| case Token.NamedVal:
171| if tok.value in self.constants:
172| return self.constants[tok.value]
173| if tok.value in self.variables:
174| return self.variables[tok.value]
175| raise ValueError(f'Uknown name: "{tok.value}"')
176|
177|
178| case Token.Operator:
179|
180| if not hasattr(self, tok.value):
181| raise ValueError(f'Unknown operator: "{tok.value}"')
182| oper = getattr(self, tok.value)
183| return oper()
184|
185|
186| case _:
187| raise RuntimeError(f'Unknown Token Type: {tok.ttype}.')
188|
189| def set (self):
190| '''Set a variable's value.'''
191|
192|
193| tok = self.tokens.pop(0)
194| if not isinstance(tok,NamedValToken):
195| SyntaxError(f'Variable name required, not {tok}.')
196|
197|
198| value = self._get_value()
199| self.variables[tok.value] = value
200|
201|
202| return value
203|
204| def func (self):
205| '''Declare a function. FUNC <name> <expr>'''
206| Log.debug('FUNC')
207|
208| func_name = self.tokens.pop(0)
209| if not isinstance(func_name,NamedValToken):
210| SyntaxError(f'Function name required, not {func_name}.')
211|
212| expression = []
213|
214| tok = self.tokens.pop(0)
215| while tok.value != 'end':
216| expression.append(tok)
217|
218| tok = self.tokens.pop(0)
219|
220|
221| self.functions[func_name.value] = expression
222|
223| for ix,tok in enumerate(expression, start=1):
224| Log.debug(f'{ix}: {tok}')
225| Log.debug()
226|
227| return expression
228|
229| def call (self):
230| '''Invoke a function. CALL <name> <args>'''
231| Log.debug('CALL')
232|
233| func_name = self.tokens.pop(0)
234| if not isinstance(func_name,NamedValToken):
235| SyntaxError(f'Function name required, not {func_name}.')
236| function = self.functions[func_name.value]
237|
238|
239| arguments = []
240| tok = self.tokens.pop(0)
241| while tok.value != 'end':
242| arguments.append(tok)
243|
244| tok = self.tokens.pop(0)
245|
246|
247| for ix,argument in enumerate(arguments, start=1):
248| Log.debug(f'{ix}: {argument}')
249| name = f'${ix}'
250| self.variables[name] = argument
251| Log.debug()
252|
253| return 0
254|
255|
256|
257| def now (self):
258| return time.time()
259|
260| def randnum (self):
261| return random.random()
262|
263|
264|
265| def inverse (self):
266| x = self._get_value()
267| return 1.0/x
268|
269| inv = inverse
270|
271| def factorial (self):
272| x = self._get_value()
273| return math.factorial(x)
274|
275| fac = factorial
276|
277| def ceiling (self):
278| x = self._get_value()
279| return math.ceil(x)
280|
281| ceil = ceiling
282|
283| def floor (self):
284| x = self._get_value()
285| return math.floor(x)
286|
287| def trunc (self):
288| x = self._get_value()
289| return math.trunc(x)
290|
291| def round (self):
292| x = self._get_value()
293| n = self._get_value()
294| return round(x, ndigits=n)
295|
296|
297|
298| def add (self):
299| a = self._get_value()
300| b = self._get_value()
301| return (a + b)
302|
303| plus = add
304|
305| def subtract (self):
306| a = self._get_value()
307| b = self._get_value()
308| return (a - b)
309|
310| sub = subtract
311|
312| def multiply (self):
313| a = self._get_value()
314| b = self._get_value()
315| return (a * b)
316|
317| mul = multiply
318| mult = multiply
319|
320| def divide (self):
321| a = self._get_value()
322| b = self._get_value()
323| return (a / b)
324|
325| div = divide
326|
327|
328|
329| def power (self):
330| x = self._get_value()
331| p = self._get_value()
332| return pow(x, p)
333|
334| pwr = power
335| pow = power
336|
337| def square (self):
338| x = self._get_value()
339| return pow(x, 2)
340|
341| sqr = square
342|
343| def squareroot (self):
344| x = self._get_value()
345| return math.sqrt(x)
346|
347| sqrt = squareroot
348|
349| def cube (self):
350| x = self._get_value()
351| return pow(x, 3)
352|
353| def cuberoot (self):
354| x = self._get_value()
355| return math.cbrt(x)
356|
357| cbrt = cuberoot
358|
359| def log (self):
360| x = self._get_value()
361| b = self._get_value()
362| return math.log(x, b)
363|
364| def ln (self):
365| x = self._get_value()
366| return math.log(x)
367|
368| def log10 (self):
369| x = self._get_value()
370| return math.log10(x)
371|
372| def log2 (self):
373| x = self._get_value()
374| return math.log2(x)
375|
376| def exp (self):
377| x = self._get_value()
378| return math.exp(x)
379|
380|
381|
382| def hypot2 (self):
383| x = self._get_value()
384| y = self._get_value()
385| return math.hypot(x, y)
386|
387| def hypot3 (self):
388| x = self._get_value()
389| y = self._get_value()
390| z = self._get_value()
391| return math.hypot(x, y, z)
392|
393| def degs (self):
394| x = self._get_value()
395| return math.degrees(x)
396|
397| def rads (self):
398| x = self._get_value()
399| return math.radians(x)
400|
401| def sin (self):
402| a = self._get_value()
403| return math.sin(a)
404|
405| def cos (self):
406| a = self._get_value()
407| return math.cos(a)
408|
409| def tan (self):
410| a = self._get_value()
411| return math.tan(a)
412|
413| def atan2 (self):
414| y = self._get_value()
415| x = self._get_value()
416| return math.atan2(y, x)
417|
418| def arcsin (self):
419| y = self._get_value()
420| return math.asin(y)
421|
422| def arccos (self):
423| x = self._get_value()
424| return math.acos(x)
425|
426| def arctan (self):
427| slope = self._get_value()
428| return math.atan(slope)
429|
430| asin = arcsin
431| acos = arccos
432| atan = arctan
433|
434|
435|
436|
437|
438| def mi2km (self):
439| x = self._get_value()
440| return (x * 1.60934)
441|
442| def km2mi (self):
443| x = self._get_value()
444| return (x * 0.621371)
445|
446| def mph2mps (self):
447| x = self._get_value()
448| return (x * 0.44704)
449|
450| def mps2mph (self):
451| x = self._get_value()
452| return (x * 2.23693629)
453|
454| def lb2kg (self):
455| x = self._get_value()
456| return (x * 0.453592)
457|
458| def kg2lb (self):
459| x = self._get_value()
460| return (x * 2.20462)
461|
462|
463|
464| def sum (self):
465| n = self._get_value()
466| total = 0
467| for _ in range(n):
468| total += self._get_value()
469| return total
470|
471| def min (self):
472| n = self._get_value()
473| minimum = None
474| for _ in range(n):
475| value = self._get_value()
476| if (minimum is None) or (value < minimum):
477| minimum = value
478| return minimum
479|
480| def max (self):
481| n = self._get_value()
482| maximum = None
483| for _ in range(n):
484| value = self._get_value()
485| if (maximum is None) or (maximum < value):
486| maximum = value
487| return maximum
488|
489| def avg (self):
490| n = self._get_value()
491| total = 0
492| for _ in range(n):
493| total += self._get_value()
494| return total/n
495|
496| @classmethod
497| def opnames (cls):
498| '''Return a list of operator names.'''
499| return list(filter(cls.isoperator, cls.__dict__))
500|
501| @classmethod
502| def isoperator (cls, name):
503| '''Return True if name is a valid operator name.'''
504|
505|
506| if name.startswith('_'):
507| return False
508|
509| if name.startswith('parse'):
510| return False
511|
512| if name in cls.SkipNames:
513| return False
514|
515|
516| return hasattr(cls, name)
517|
518| @classmethod
519| def datum (cls, word):
520| '''Determine and return appropriate token type.'''
521|
522|
523| if word == 'end':
524| return SpecialToken(word)
525|
526|
527| if cls.isoperator(word):
528| return OperatorToken(word)
529|
530|
531| try:
532| return DatumToken(int(word, base=0))
533| except:
534| pass
535|
536|
537| try:
538| return DatumToken(float(word))
539| except:
540| pass
541|
542|
543|
544| return NamedValToken(word)
545|
546| @classmethod
547| def parse_words (cls, words):
548| return [Calculator.datum(word) for word in words]
549|
550| @classmethod
551| def parse_text (cls, text):
552| words = text.split()
553| return cls.parse_words(words)
554|
555|
556|
557| def expand_decimal (nbr):
558| sgn,ds,ex = nbr.as_tuple()
559| dif = len(ds) + ex
560| Log.trace(f'{dif=}')
561|
562| if dif < 0:
563| digs = (0,)*abs(abs(ex)-len(ds)) + ds
564| return '0.'+''.join(str(d) for d in digs)
565| if 0 < dif:
566| digs = ''.join(str(d) for d in ds)
567| return f'{digs[:dif]}.{digs[dif:]}'
568|
569| digs = ''.join(str(d) for d in ds)
570| return f'0.{digs}'
571|
572|
573| def dec_pi ():
574| """Compute Pi to the current precision."""
575| dec.getcontext().prec += 2
576|
577| three = dec.Decimal(3)
578| lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
579|
580| while s != lasts:
581| lasts = s
582| n, na = n+na, na+8
583| d, da = d+da, da+32
584| t = (t * n) / d
585| s += t
586|
587| dec.getcontext().prec -= 2
588| return +s
589|
590|
591| def dec_cos (x):
592| """Return the cosine of x as measured in radians.
592|
592| The Taylor series approximation works best for a small value of x.
592| For larger values, first compute x = x % (2 * pi).
592|
592| >>> print(dec_cos(Decimal('0.5')))
592| 0.8775825618903727161162815826
592| >>> print(dec_cos(0.5))
592| 0.87758256189
592| >>> print(dec_cos(0.5+0j))
592| (0.87758256189+0j)
592|
592| """
593| dec.getcontext().prec += 2
594|
595| i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
596|
597| while s != lasts:
598| lasts = s
599| i += 2
600| fact *= i * (i-1)
601| num *= x * x
602| sign *= -1
603| s += num / fact * sign
604|
605| dec.getcontext().prec -= 2
606| return +s
607|
608|
609| def dec_sin (x):
610| """Return the sine of x as measured in radians.
610|
610| The Taylor series approximation works best for a small value of x.
610| For larger values, first compute x = x % (2 * pi).
610|
610| >>> print(dec_sin(Decimal('0.5')))
610| 0.4794255386042030002732879352
610| >>> print(dec_sin(0.5))
610| 0.479425538604
610| >>> print(dec_sin(0.5+0j))
610| (0.479425538604+0j)
610|
610| """
611| dec.getcontext().prec += 2
612|
613| i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
614|
615| while s != lasts:
616| lasts = s
617| i += 2
618| fact *= i * (i-1)
619| num *= x * x
620| sign *= -1
621| s += num / fact * sign
622|
623| dec.getcontext().prec -= 2
624| return +s
625|
626|
627| class DecimalCalculator:
628| """Prefix Decimal Calculator class.
628|
628| Implements a script-based pre-fix math calculator.
628|
628| Attributes:
628| tokens list of tokens to process
628| variables dictionary of variables
628| constants dictionary of constants
628| result list of outputs
628|
628| Methods:
628| reset reset calculator
628| execute execute tokens
628| <operator> various methods implementing each operator
628| _get_value get next token value; evaluates operators
628|
628| Class Methods:
628| opnames return list of operator names
628| isoperator determines whether a name is an operator
628| datum given a word, return an appropriate token
628| parse_words given list of words, return list of tokens
628| parse_text given text, return list of tokens
628| """
629|
630| SkipNames = [
631| "opnames", "isoperator", "datum", "reset", "execute",
632| 'tokens', 'variables', 'constants', 'result',
633| "SkipNames"
634| ]
635|
636| def __init__ (self, tokens=None, variables=None, prec=50):
637| '''New instance.'''
638| dec.getcontext().prec = prec
639|
640| self.tokens = [] if tokens is None else list(tokens)
641| self.variables = {} if variables is None else variables
642| self.constants = {
643| 'e': dec.Decimal('1.0').exp(),
644| 'pi': dec_pi(),
645| 'tau': dec_pi()+dec_pi(),
646| 'PL': dec.Decimal('1.61625e-35'),
647| 'h': dec.Decimal('6.62607015e-34'),
648| 'hbar': dec.Decimal('1.054571817e-34'),
649| 'c': dec.Decimal('299_792_458'),
650| 'c2': dec.Decimal('89_875_517_873_681_764'),
651| 'LY': dec.Decimal('9_460_730_472_580_800'),
652| }
653| self.results = []
654|
655| def __repr__ (self):
656| '''Debug string.'''
657| return f'<{type(self).__name__} @{id(self):012x}>'
658|
659| def __str__ (self):
660| '''String version.'''
661| return ' '.join(self.tokens)
662|
663| @classmethod
664| def opnames (cls):
665| '''Return a list of operator names.'''
666| return list(filter(cls.isoperator, cls.__dict__))
667|
668| @classmethod
669| def isoperator (cls, name):
670| '''Return True if name is a valid operator name.'''
671|
672|
673| if name.startswith('_'):
674| return False
675|
676| if name.startswith('parse'):
677| return False
678|
679| if name in cls.SkipNames:
680| return False
681|
682|
683| return hasattr(cls, name)
684|
685| @classmethod
686| def datum (cls, word):
687| '''Determine and return appropriate token type.'''
688|
689|
690| if cls.isoperator(word):
691| return OperatorToken(word)
692|
693|
694| try:
695| value = int(word, base=0)
696| return DatumToken(dec.Decimal(word))
697| except:
698| pass
699|
700|
701| try:
702| value = float(word)
703| return DatumToken(dec.Decimal(word))
704| except:
705| pass
706|
707|
708|
709| return NamedValToken(word)
710|
711| @classmethod
712| def parse_words (cls, words):
713| return [cls.datum(word) for word in words]
714|
715| @classmethod
716| def parse_text (cls, text):
717| words = text.split()
718| return cls.parse_words(words)
719|
720| def reset (self):
721| '''Reset.'''
722| self.variables = {}
723| self.results = []
724|
725| def execute (self, tokens=None):
726| '''Execute the list of tokens as a formula.'''
727| if tokens is not None:
728| self.tokens = list(tokens)
729|
730|
731| self.reset()
732|
733|
734| if not self.tokens:
735| self.results = ['<null>']
736| return
737|
738|
739| while len(self.tokens):
740|
741| value = self._get_value()
742|
743| self.results.append(value)
744|
745|
746| return self.results[-1]
747|
748| def _get_value (self):
749| '''Get next token value; evaluates operators.'''
750| if len(self.tokens) == 0:
751| raise RuntimeError('No tokens.')
752|
753|
754| tok = self.tokens.pop(0)
755|
756|
757| match tok.ttype:
758|
759|
760| case Token.Constant:
761| return tok.value
762|
763|
764| case Token.NamedVal:
765| if tok.value in self.constants:
766| return self.constants[tok.value]
767| if tok.value in self.variables:
768| return self.variables[tok.value]
769| raise ValueError(f'Uknown name: "{tok.value}"')
770|
771|
772| case Token.Operator:
773|
774| if not hasattr(self, tok.value):
775| raise ValueError(f'Unknown operator: "{tok.value}"')
776| oper = getattr(self, tok.value)
777| return oper()
778|
779|
780| case _:
781| raise RuntimeError(f'Unknown Token Type: {tok.ttype}.')
782|
783| def set (self):
784| '''Set a variable's value.'''
785|
786|
787| tok = self.tokens.pop(0)
788| if not isinstance(tok,NamedValToken):
789| SyntaxError(f'Variable name required, not {tok.value}.')
790|
791|
792| value = self._get_value()
793| self.variables[tok.value] = value
794|
795|
796| return value
797|
798|
799|
800| def now (self):
801| return dec.Decimal(str(time.time()))
802|
803| def randnum (self):
804| return dec.Decimal(str(random.random()))
805|
806|
807|
808| def inverse (self):
809| x = self._get_value()
810| return dec.Decimal('1.0') / x
811|
812| inv = inverse
813|
814|
815|
816| def add (self):
817| a = self._get_value()
818| b = self._get_value()
819| return (a + b)
820|
821| plus = add
822|
823| def subtract (self):
824| a = self._get_value()
825| b = self._get_value()
826| return (a - b)
827|
828| sub = subtract
829|
830| def multiply (self):
831| a = self._get_value()
832| b = self._get_value()
833| return (a * b)
834|
835| mul = multiply
836| mult = multiply
837|
838| def divide (self):
839| a = self._get_value()
840| b = self._get_value()
841| return (a / b)
842|
843| div = divide
844|
845|
846|
847| def square (self):
848| x = self._get_value()
849| return (x * x)
850|
851| sqr = square
852|
853| def squareroot (self):
854| x = self._get_value()
855| return x.sqrt()
856|
857| sqrt = squareroot
858|
859| def cube (self):
860| x = self._get_value()
861| return (x * x * x)
862|
863| def ln (self):
864| x = self._get_value()
865| return x.ln()
866|
867| def log10 (self):
868| x = self._get_value()
869| return x.log10()
870|
871| def log2 (self):
872| x = self._get_value()
873| return x.logb()
874|
875|
876|
877| def degs (self):
878| raise NotImplementedError()
879|
880| def rads (self):
881| raise NotImplementedError()
882|
883| def sin (self):
884| a = self._get_value()
885| return dec_sin(a)
886|
887| def cos (self):
888| a = self._get_value()
889| return dec_cos(a)
890|
891|
892|
893| def mi2km (self):
894| x = self._get_value()
895| return (x * dec.Decimal('1.60934'))
896|
897| def km2mi (self):
898| x = self._get_value()
899| return (x * dec.Decimal('0.621371'))
900|
901| def mph2mps (self):
902| x = self._get_value()
903| return (x * dec.Decimal('0.44704'))
904|
905| def mps2mph (self):
906| x = self._get_value()
907| return (x * dec.Decimal('2.23693629'))
908|
909| def lb2kg (self):
910| x = self._get_value()
911| return (x * dec.Decimal('0.453592'))
912|
913| def kg2lb (self):
914| x = self._get_value()
915| return (x * dec.Decimal('2.20462'))
916|
917|
918|
919| def sum (self):
920| n = self._get_value()
921| total = dec.Decimal('0')
922| for _ in range(n):
923| total += self._get_value()
924| return total
925|
926| def min (self):
927| n = self._get_value()
928| minimum = None
929| for _ in range(n):
930| value = self._get_value()
931| if (minimum is None) or (value < minimum):
932| minimum = value
933| return minimum
934|
935| def max (self):
936| n = self._get_value()
937| maximum = None
938| for _ in range(n):
939| value = self._get_value()
940| if (maximum is None) or (maximum < value):
941| maximum = value
942| return maximum
943|
944| def avg (self):
945| n = self._get_value()
946| total = dec.Decimal('0')
947| for _ in range(n):
948| total += self._get_value()
949| return total/n
950|
951|
952|
953| DIG0 = ord('0')
954| UCA = ord('A')
955| LCA = ord('a')
956|
957|
958| class AlphaMap (dict):
959| """String Translate Alpha Filter."""
960|
961| def __init__ (self, others=""):
962| '''New AlphaMap instance.'''
963| self[ord('.')] = '.'
964| self[ord('_')] = '_'
965|
966|
967| for cx in range(26):
968| self[UCA+cx] = chr(UCA+cx)
969| self[LCA+cx] = chr(LCA+cx)
970|
971|
972| for cx in range(10):
973| self[DIG0+cx] = chr(DIG0+cx)
974|
975|
976| for ch in others:
977| cx = ord(ch)
978| assert 0 <= cx < 256, ValueError(f'Illegal character: "{ch}"')
979| self[cx] = ch
980|
981| def __missing__ (self, cx):
982| """All other characters map to spaces."""
983| return " "
984|
985|
986| class WordCounter:
987| '''Word-Counter "Calculator".
987|
987| A basic word-counter to replace the Calculator class.
987| This class replicates the attributes and methods of
987| the Calculator class but just counts words.
987|
987| Attributes:
987| tokens list of words to count
987| variables unused but expected
987| constants unused but expected
987| result output string
987|
987| Methods:
987| reset reset calculator
987| execute execute tokens
987|
987| Class Methods:
987| opnames returns empty list
987| parse_text given text, return list of words
987|
987| '''
988| def __init__ (self, **kwargs):
989| '''New instance.'''
990| self.tokens = []
991| self.variables = {}
992| self.constants = []
993| self.results = ['']
994|
995| def __repr__ (self):
996| '''Debug string.'''
997| return f'<{typename(self)} @{id(self):012x}>'
998|
999| def __str__ (self):
1000| '''String version.'''
1001| return ' '.join(self.tokens)
1002|
1003| def reset (self):
1004| '''Reset.'''
1005| self.results = ['']
1006|
1007| def execute (self, words=''):
1008| '''Count the list of words.'''
1009| self.tokens = words
1010| self.unique = list(sorted(set(words)))
1011| self.nw = len(self.tokens)
1012| self.nu = len(self.unique)
1013| self.nc = sum(len(word) for word in self.tokens)
1014| text = f'{self.nw} words ({self.nu} unique), {self.nc} chars'
1015| self.results = [text]
1016| return text
1017|
1018| @classmethod
1019| def parse_text (cls, text):
1020| '''Break text into words. Remove all punctuation.'''
1021| txt = text.translate(AlphaMap())
1022| txt = txt.replace('. ', ' ')
1023| if txt.endswith('.'): txt = txt[:-1]
1024| txt = txt.lower()
1025| return txt.split()
1026|
1027| @classmethod
1028| def opnames (cls):
1029| '''No operators but an expected method.'''
1030| return []
1031|
1032|
1033|
1034| FileTypes = [
1035| ('Calc files', '*.calc;*.dcalc'),
1036| ('Input files', '*.in'),
1037| ('Text files', '*.txt;*.text'),
1038| ("all files", "*")
1039| ]
1040|
1041|
1042| AboutText = '''\
1042| Tk Calculator.
1042|
1042| A little demo of Python's Tk suite
1042| for making windows apps. (As well
1042| as being a demo of a script-driven
1042| pre-fix math calculator.)
1042|
1042| © Wyrd Smythe December 2025
1042| '''
1043|
1044|
1045| '''Keys to settings file parameters (parameter names).'''
1046| UltimateKey = 'hitchhiker'
1047| LastFileKey = 'lastfile'
1048| FontSourcekey = 'font.source'
1049| FontResultKey = 'font.result'
1050|
1051| '''Default dictionaries for supplying default parameters.'''
1052| DfltUltimate = jcfg.JConfigItem.make_dict(42, "The ultimate answer!", "But what's the question?", 'int')
1053| DfltLastFile = jcfg.JConfigItem.make_dict('', "", "", 'str')
1054| DfltFontSource = jcfg.JConfigItem.make_dict('Courier New, 13', "Font for source text (default: 'Courier New, 13').", "format: <fontname>, <fontsize> [, <fontstyles>]*", 'str')
1055| DfltFontResult = jcfg.JConfigItem.make_dict('Arial, 14, bold', "Font for result text (default: 'Arial, 14, bold').", "format: <fontname>, <fontsize> [, <fontstyles>]*", 'str')
1056|
1057|
1058| class AppConfigSet (jcfg.JConfigSettingsSet):
1059| '''Settings class for GREP.'''
1060|
1061| def __init__ (self, name, params, papasan):
1062| '''New AppConfigSet instance.'''
1063| Log.debug(f'AppConfigSet({name}, {params}, {typename(papasan)})')
1064| super().__init__(name, params, papasan)
1065|
1066| self.ultimate = self.getsetparam(UltimateKey, DfltUltimate)
1067| self.last_file = self.getsetparam(LastFileKey, DfltLastFile)
1068| self.source_font = self.getsetparam(FontSourcekey, DfltFontSource)
1069| self.result_font = self.getsetparam(FontResultKey, DfltFontResult)
1070|
1071| @property
1072| def lastfile (self): return self.last_file
1073|
1074| @property
1075| def srcfont (self): return self.source_font
1076|
1077| @property
1078| def resfont (self): return self.result_font
1079|
1080|
1081| class AppSettings (jcfg.JConfigSettings):
1082| '''Configuration class for GREP.'''
1083|
1084|
1085| NewSetType = AppConfigSet
1086|
1087| def __init__ (self, **kwargs):
1088| '''New AppSettings instance.'''
1089| Log.debug(f'AppSettings()')
1090| super().__init__(**kwargs)
1091|
1092|
1093|
1094| class Application:
1095| '''Tk Calculator Application class.
1095|
1095| Implements a multi-line textbox for a user script and delegates
1095| to a backend calculator (or other engine) to execute the script.
1095|
1095| Create a new Application:
1095| app = Application(file='', mode='calc')
1095|
1095| if file is provided, calculator loads named file
1095| if mode is provided, calculator loads named mode
1095|
1095| Attributes:
1095| filename ~str: name of current source file
1095| mode ~str: type of calculator to be
1095| dirty ~bool: current textbox text has been modified
1095| nofile ~bool: no file loaded or save-as
1095| calc ~Calculator object
1095| title ~str: window title
1095| settings_path ~str: path to settings file (or '')
1095| settings_name ~str: name of settings file (may include path)
1095| opts ~str: name of settings configuration to use
1095| settings ~JConfigSettings: application options object
1095| root ~Tk: application window root
1095| wndw ~Frame: application window frame
1095| head ~Frame: application frame
1095| main ~Frame: application frame
1095| sbar ~Frame: application frame
1095| result ~Tk string variable for result textbox
1095| output ~Tk Entry for result display
1095| source ~Tk ScrolledText for source text
1095| status ~Tk Label for status results
1095| mbar ~Tk Menu for menubar
1095| <various> ~other Tk widgets used in app
1095|
1095| Methods:
1095| calculate ~execute the script
1095| open_source_file ~open and load a source code file
1095| load_source_file ~load a source code file into Textbox
1095| save_source_file ~save the Textbox text to a text file
1095| update_title ~update the window title (with new filename)
1095| update_status ~write to the result
1095|
1095| file_new ~menu:File/New
1095| file_open ~menu:File/Open...
1095| file_save ~menu:File/Save
1095| file_save_as ~menu:File/Save As...
1095| copy_source ~menu:Edit/Copy Source
1095| copy_result ~menu:Edit/Copy Result
1095| view_results ~menu:View/Results
1095| view_variables ~menu:View/Variables
1095| view_operators ~menu:View/Operators
1095| help_about ~menu:Help/About
1095|
1095| app_exit ~exit application; destory window(s)
1095| app_keypress ~application key handler
1095| txt_keypress ~textbox key handler
1095|
1095| _create_widgets ~create various widgets
1095| _create_menubar ~create menubar
1095| '''
1096| def __init__ (self, **kwargs):
1097| '''New Application instance.'''
1098| self.filename = KWARG('file', '', str, kwargs)
1099| self.mode = KWARG('mode', 'calc', str, kwargs)
1100| self.title = KWARG('title', 'Tk App', str, kwargs)
1101| self.opts = KWARG('opts' , 'default', str, kwargs)
1102| self.settings_path = KWARG('spath', CnfgPath, str, kwargs)
1103| self.settings_name = KWARG('sname', 'tk-calc.cnfg', str, kwargs)
1104| Log.info(f'Tk-Calc:: {str(list(kwargs.keys()))}')
1105| Log.debug(f'{self.mode=}')
1106| Log.debug(f'{self.filename=}')
1107| Log.debug(f'{self.title=}')
1108| Log.debug(f'{self.settings_path=}')
1109| Log.debug(f'{self.settings_name=}')
1110| Log.debug(f'{self.opts=}')
1111| Log.info()
1112| self.dirty = False
1113| self.nofile = True
1114|
1115| self.settings = AppSettings(cfg=self.opts, fname=self.settings_name, fpath=self.settings_path)
1116| Log.debug(f'settings: {self.settings!r}')
1117| Log.debug(f'> current: {self.settings.name}')
1118| Log.debug(f'> configs: {self.settings.cnfgkeys}')
1119| Log.debug(f'> currcnfg: {self.settings.current!r}')
1120| Log.debug(f'> parmkeys: {self.settings.current.paramkeys}')
1121| Log.debug(f'> wndwpos: {self.settings.current.xpos:4d}x{self.settings.current.ypos:4d}')
1122| Log.debug(f'> wndwdim: {self.settings.current.xdim:4d}x{self.settings.current.ydim:4d}')
1123| Log.debug(f'> wndwmin: {self.settings.current.xmin:4d}x{self.settings.current.ymin:4d}')
1124| Log.debug(f'> wndwmax: {self.settings.current.xmax:4d}x{self.settings.current.ymax:4d}')
1125| Log.debug(f'> srcfont: {self.settings.current.srcfont!r}')
1126| Log.debug(f'> resfont: {self.settings.current.resfont!r}')
1127| Log.debug(f'> lastfile: {self.settings.current.lastfile!r}')
1128| Log.debug()
1129|
1130|
1131| match self.mode:
1132| case 'wc':
1133| self.calc = WordCounter()
1134| case 'dec':
1135| self.calc = DecimalCalculator()
1136| case _:
1137| self.calc = Calculator()
1138|
1139|
1140| self._create_widgets()
1141| self._create_menubar()
1142|
1143|
1144| if self.filename:
1145| self.open_source_file()
1146|
1147| self.update_title()
1148| self.update_status(f'Mode: {self.mode}', '#7fffaf')
1149|
1150|
1151| self.root.deiconify()
1152|
1153|
1154| self.source.focus()
1155|
1156| def app_exit (self, *args):
1157| '''Exit application; destory window(s).'''
1158| Log.debug('Exit()')
1159| if self.dirty:
1160| ansr = msgbox.askyesno('Text is not saved.', 'Save first?')
1161| if ansr:
1162| self.file_save()
1163| return
1164|
1165|
1166| geo = util.TkGeometry.from_string(self.root.wm_geometry())
1167| maxsize = self.root.wm_maxsize()
1168| minsize = self.root.wm_minsize()
1169|
1170|
1171| self.settings.current[jcfg.JConfigSettingsPosX].value = geo.xpos
1172| self.settings.current[jcfg.JConfigSettingsPosY].value = geo.ypos
1173| self.settings.current[jcfg.JConfigSettingsDimX].value = geo.xdim
1174| self.settings.current[jcfg.JConfigSettingsDimY].value = geo.ydim
1175| self.settings.current[jcfg.JConfigSettingsMaxX].value = maxsize[0]
1176| self.settings.current[jcfg.JConfigSettingsMaxY].value = maxsize[1]
1177| self.settings.current[jcfg.JConfigSettingsMinX].value = minsize[0]
1178| self.settings.current[jcfg.JConfigSettingsMinY].value = minsize[1]
1179| self.settings.current[jcfg.JConfigSettingsMinY].value = minsize[1]
1180| self.settings.current[LastFileKey] = self.filename
1181|
1182|
1183| fn = makefilename(self.settings_path, self.settings_name)
1184| self.settings.save_json_file(fn)
1185|
1186|
1187| self.root.destroy()
1188|
1189| def calculate (self, *args):
1190| '''Execute the script.'''
1191| self.update_status('Calculating...', '#7f7f7f')
1192| self.calc.reset()
1193|
1194|
1195| text = self.source.get('1.0','end')
1196| if not text:
1197| msgbox.showwarning('No text.', 'Nothing to calculate.')
1198| return
1199|
1200| try:
1201|
1202| tokens = self.calc.parse_text(text)
1203|
1204|
1205| answer = self.calc.execute(tokens)
1206|
1207| except Exception as e:
1208| self.result.set('#ERROR#')
1209| self.update_status(e, '#ff3322')
1210| else:
1211| self.result.set(answer)
1212| self.update_status('Done.')
1213|
1214| def open_source_file (self):
1215| '''Open and load a source code text file into the Textbox.'''
1216|
1217| fp = open(self.filename, mode='r', encoding='utf8')
1218| try:
1219| text = fp.read()
1220| except Exception as e:
1221| self.update_status(e, '#ff3322')
1222| finally:
1223| fp.close()
1224|
1225|
1226| self.load_source_file(text)
1227|
1228| def load_source_file (self, text):
1229| '''Load a source code text file into the Textbox.'''
1230|
1231| self.calc.reset()
1232| self.result.set('')
1233| self.dirty = False
1234| self.nofile = False
1235|
1236| self.source.delete('1.0', 'end')
1237| self.source.insert('1.0', text)
1238| self.source.edit_modified(0)
1239|
1240| self.update_title()
1241| self.update_status(f'opened: {self.filename} ({len(text)} chars)')
1242|
1243| def save_source_file (self):
1244| '''Save the Textbox text to a text file.'''
1245| text = self.source.get('1.0','end')
1246| self.source.edit_modified(0)
1247| if not text:
1248| msgbox.showwarning('No text.', 'Nothing to save.')
1249| return
1250| fp = open(self.filename, mode='w', encoding='utf8')
1251| try:
1252| fp.write(text)
1253| except Exception as e:
1254| self.update_status(e, '#ff3322')
1255| finally:
1256| fp.close()
1257| self.dirty = False
1258| self.nofile = False
1259| self.update_title()
1260| self.update_status(f'saved: {self.filename} ({len(text)} chars)')
1261|
1262| def update_title (self):
1263| '''Update the window title (with new filename).'''
1264| name = f'[{path.basename(self.filename)}]' if self.filename else ''
1265| flag = '***' if self.dirty else ''
1266| self.root.title(f'Tk Calculator {name}{flag}')
1267|
1268| def update_status (self, message, color='#ffffff'):
1269| '''Write to the status bar.'''
1270| self.status['text'] = message
1271| self.status['foreground'] = color
1272|
1273| def file_new (self, *args):
1274| '''Menu: File/New.'''
1275| Log.debug('File/New()')
1276| if self.dirty:
1277| ansr = msgbox.askyesno('Text is not saved.', 'Save first?')
1278| if ansr:
1279| self.file_save()
1280| return
1281|
1282| self.calc.reset()
1283| self.result.set('')
1284| self.source.delete('1.0', 'end')
1285| self.source.edit_modified(0)
1286| self.filename = ''
1287| self.dirty = False
1288| self.nofile = True
1289| self.update_title()
1290| self.update_status('(new)')
1291|
1292| def file_open (self, *args):
1293| '''Menu: File/Open.'''
1294| Log.debug('File/Open()')
1295| if self.dirty:
1296| ansr = msgbox.askyesno('Text is not saved.', 'Save first?')
1297| if ansr:
1298| self.file_save()
1299| return
1300| props = dict(
1301| parent=self.root,
1302| title="Select an input file:",
1303| filetypes=FileTypes,
1304| defaultextension='calc',
1305| initialdir=path.dirname(self.filename),
1306| initialfile=path.basename(self.filename),
1307| mode='r',
1308|
1309| )
1310| fileobj = dialog.askopenfile(**props)
1311| Log.debug(f'{fileobj=}:{typename(fileobj)}')
1312| if fileobj:
1313|
1314| self.filename = fileobj.name
1315|
1316|
1317| self.load_source_file(fileobj.read())
1318|
1319| def file_save (self, *args):
1320| '''Menu: File/Save.'''
1321| Log.debug('File/Save()')
1322| if self.nofile:
1323| self.file_save_as()
1324| return
1325| self.save_source_file()
1326|
1327| def file_save_as (self, *args):
1328| '''Menu: File/Save As...'''
1329| Log.debug('File/SaveAs()')
1330| props = dict(
1331| parent=self.root,
1332| title="Enter a save-as filename:",
1333| filetypes=FileTypes,
1334| defaultextension='calc',
1335| initialdir=path.dirname(self.filename),
1336| initialfile=path.basename(self.filename),
1337| confirmoverwrite=1,
1338| )
1339| filename = dialog.asksaveasfilename(**props)
1340| Log.debug(f'{filename=}')
1341| if 0 < len(filename):
1342| self.filename = filename
1343| self.save_source_file()
1344|
1345| def copy_source (self):
1346| '''Menu: Edit/Copy Source.'''
1347| txt = self.source.get('1.0','end').strip()
1348| if not txt:
1349| msgbox.showwarning('No source text!','Nothing to copy!')
1350| return
1351| self.root.clipboard_clear()
1352| self.root.clipboard_append(txt)
1353| self.update_status('Copied source text to clipboard.')
1354|
1355| def copy_result (self):
1356| '''Menu: Edit/Copy Result.'''
1357| txt = self.result.get()
1358| if not txt:
1359| msgbox.showwarning('No result text!','Nothing to copy!')
1360| return
1361| self.root.clipboard_clear()
1362| self.root.clipboard_append(txt)
1363| self.update_status('Copied result text to clipboard.')
1364|
1365| def view_results (self):
1366| '''Menu: View/Results.'''
1367| lines = [str(res) for res in self.calc.results]
1368| msgbox.showinfo('All Results', '\n'.join(lines))
1369|
1370| def view_variables (self):
1371| '''Menu: View/Variables.'''
1372| lines = [f'{n} = {v}' for n,v in self.calc.variables.items()]
1373| msgbox.showinfo('Variables', '\n'.join(lines))
1374|
1375| def view_operators (self):
1376| '''Menu: View/Operators.'''
1377| names = list(sorted(self.calc.opnames()))
1378| text = ', '.join(names)
1379| msgbox.showinfo('Operators', f'{text} ({len(names)})')
1380|
1381| def help_about (self, *args):
1382| '''Menu: Help/About.'''
1383| Log.debug('Help/About()')
1384| msgbox.showinfo('About', AboutText)
1385|
1386| def app_test (self, *args):
1387| '''For testing.'''
1388| Log.debug(f'Test({list2str(args,",")})')
1389| Log.debug()
1390|
1391| def printm_if_u_gotm (evt, name):
1392| if hasattr(evt, name):
1393| Log.debug(f'{name}: {evt.__dict__[name]}')
1394|
1395| if isinstance(args[0], tk.Event):
1396| evt = args[0]
1397| printm_if_u_gotm(evt, 'serial')
1398| printm_if_u_gotm(evt, 'time')
1399| printm_if_u_gotm(evt, 'type')
1400| printm_if_u_gotm(evt, 'widget')
1401| printm_if_u_gotm(evt, 'state')
1402| printm_if_u_gotm(evt, 'keycode')
1403| printm_if_u_gotm(evt, 'keysym')
1404| printm_if_u_gotm(evt, 'keysym_num')
1405| printm_if_u_gotm(evt, 'char')
1406| printm_if_u_gotm(evt, 'num')
1407| printm_if_u_gotm(evt, 'x')
1408| printm_if_u_gotm(evt, 'y')
1409| printm_if_u_gotm(evt, 'x_root')
1410| printm_if_u_gotm(evt, 'y_root')
1411| printm_if_u_gotm(evt, 'delta')
1412| printm_if_u_gotm(evt, 'focus')
1413| printm_if_u_gotm(evt, 'height')
1414| printm_if_u_gotm(evt, 'width')
1415| Log.debug()
1416|
1417| def txt_keypress (self, evt):
1418| '''Textbox key handler.'''
1419| if self.source.edit_modified():
1420| if not self.dirty:
1421| self.dirty = True
1422| self.update_title()
1423|
1424| def app_keypress (self, evt):
1425| '''Application key handler.
1425|
1425| Key Bindings:
1425| File/New Ctrl+N
1425| File/Open Ctrl+O
1425| File/Save Ctrl+S
1425| File/Save As Alt+S
1425| File/Exit Alt+X
1425| Edit/Copy Source Alt+C
1425| Edit/Copy Result Alt+R
1425| View/Results F1
1425| View/Variables F2
1425| View/Operators F4
1425| Help/About F12
1425|
1425| '''
1426|
1427| if evt.state & util.KEYPRESS_ALT:
1428| if evt.keysym in ['C','c']:
1429| self.copy_source()
1430| return
1431| if evt.keysym in ['R','r']:
1432| self.copy_result()
1433| return
1434| if evt.keysym in ['S','s']:
1435| self.file_save_as()
1436| return
1437| if evt.keysym in ['X','x']:
1438| self.app_exit('Alt-X')
1439| return
1440|
1441| return
1442|
1443|
1444| if evt.state & util.KEYPRESS_CTRL:
1445| if evt.keysym in ['N','n']:
1446| self.file_new()
1447| return
1448| if evt.keysym in ['O','o']:
1449| self.file_open()
1450| return
1451| if evt.keysym in ['S','s']:
1452| self.file_save()
1453| return
1454|
1455| return
1456|
1457|
1458| if evt.state & util.KEYPRESS_SHIFT:
1459|
1460| return
1461|
1462|
1463| if evt.keysym == 'F1':
1464| self.view_results()
1465| return
1466| if evt.keysym == 'F2':
1467| self.view_variables()
1468| return
1469| if evt.keysym == 'F4':
1470| self.view_operators()
1471| return
1472| if evt.keysym == 'F12':
1473| self.about()
1474| return
1475|
1476| def _create_widgets (self):
1477| '''Create various widgets.'''
1478| Log.info('Create Widgets...')
1479| status_font = ('Verdana', 8)
1480|
1481|
1482| Log.info('Create Window...')
1483| self.root = tk.Tk()
1484| self.root.withdraw()
1485| self.root.geometry(self.settings.current.geometry)
1486| self.root.minsize(*self.settings.current.wmin)
1487| self.root.maxsize(*self.settings.current.wmax)
1488|
1489| self.root.configure(bg='#336699')
1490| self.root.bind('<Escape>' , self.app_exit)
1491| self.root.bind('<F5>' , self.calculate)
1492| self.root.bind('<KeyPress>' , self.app_keypress)
1493|
1494|
1495| self.style = ttk.Style(self.root)
1496| self.style.theme_use('clam')
1497|
1498| self.style.configure('TEntry',
1499| fieldbackground='#000000',
1500| background='#000000', foreground='#00ff00',
1501| padding=(7,0)
1502| )
1503|
1504| self.result = tk.StringVar()
1505|
1506|
1507| self.wndw = tk.Frame(self.root, bg='#666666', relief='solid')
1508| self.head = tk.Frame(self.wndw, bg='#996633', relief='sunken')
1509| self.main = tk.Frame(self.wndw, bg='#336699', relief='sunken')
1510| self.sbar = tk.Frame(self.wndw, bg='#999999', relief='sunken')
1511|
1512|
1513| self.label1 = tk.Button(self.head)
1514| self.label1.config(text='Result:')
1515| self.label1.config(font=('Segoe UI',12))
1516| self.label1.config(justify='left')
1517| self.label1.config(command=self.calculate)
1518| self.label1.pack(
1519| side='left', anchor='e',
1520| padx=0, pady=0, ipadx=4, ipady=0
1521| )
1522|
1523| self.output = ttk.Entry(self.head)
1524| self.output.config(font=('Segoe UI Variable',14,'bold'))
1525| self.output.config(justify='left')
1526| self.output.config(textvariable=self.result)
1527| self.output.state(['readonly'])
1528| self.output.pack(
1529| side='right', anchor='w',
1530| fill='both', expand=True, padx=0, pady=0
1531| )
1532|
1533|
1534| self.source = ScrolledText(self.main)
1535| self.source.config(wrap=tk.WORD, tabs='30p')
1536| self.source.config(font=('Lucida Sans Typewriter',13))
1537| self.source.bind('<KeyPress>', self.txt_keypress)
1538| self.source.pack(side='top', fill='both', expand=True)
1539|
1540|
1541| self.status = tk.Label(self.sbar)
1542| self.status.config(background='#000000')
1543| self.status.config(foreground='#ffffff')
1544| self.status.config(relief='flat')
1545| self.status.config(font=('Segoe UI Variable',9))
1546| self.status.config(anchor='w')
1547| self.status.pack(side='left', fill='x', expand=True, ipadx=4)
1548|
1549| self.copyright = tk.Label(self.sbar)
1550| self.copyright.config(text="© 2025")
1551| self.copyright.config(background='#000000')
1552| self.copyright.config(foreground='#66ccff')
1553| self.copyright.config(relief='flat')
1554| self.copyright.config(font=('Segoe UI Variable',9))
1555| self.copyright.config(justify='center')
1556| self.copyright.pack(side='right', ipadx=4)
1557|
1558|
1559| self.wndw.pack(side='top', fill='both',expand=True, padx=5,pady=5)
1560| self.sbar.pack(side='bottom', fill='x', padx=1,pady=1)
1561| self.head.pack(side='top', fill='x')
1562| self.main.pack(side='top', fill='both',expand=True)
1563|
1564| def _create_menubar (self):
1565| '''Create menubar.'''
1566| Log.info('Create Menubar...')
1567| props = lambda u,a,c:dict(underline=u, accelerator=a, command=c)
1568|
1569| kw = lambda t,u,a,c: dict(
1570| label=t, underline=u, accelerator=a, command=c
1571| )
1572| def app_test_proxy (txt):
1573| '''Call app_test function with an id.'''
1574| return lambda: self.app_test(txt)
1575|
1576|
1577| self.mbar = tk.Menu(self.root)
1578|
1579|
1580| self.mbarFile = tk.Menu(self.mbar, name='fileMenu', tearoff=0, postcommand=app_test_proxy('M:File'))
1581| self.mbarFile.add_command(**kw('New' , 0, 'Ctrl+N', self.file_new))
1582| self.mbarFile.add_command(**kw('Open...' , 0, 'Ctrl+O', self.file_open))
1583| self.mbarFile.add_command(**kw('Save' , 0, 'Ctrl+S', self.file_save))
1584| self.mbarFile.add_command(**kw('Save As...', 5, 'Alt+S' , self.file_save_as))
1585| self.mbarFile.add_separator()
1586| self.mbarFile.add_command(**kw('Exit', 1, 'Alt+X', self.app_exit))
1587|
1588|
1589| self.mbarEdit = tk.Menu(self.mbar, name='editMenu', tearoff=0, postcommand=app_test_proxy('Menu.Edit'))
1590| self.mbarEdit.add_command(**kw('Copy Result', 0, 'Alt+R', self.copy_result))
1591| self.mbarEdit.add_command(**kw('Copy Source', 5, 'Alt+C', self.copy_source))
1592|
1593|
1594| self.mbarView = tk.Menu(self.mbar, name='viewMenu', tearoff=0, postcommand=app_test_proxy('Menu.View'))
1595| self.mbarView.add_command(**kw('All Results',0,'F1',self.view_results))
1596| self.mbarView.add_command(**kw('Variables' ,0,'F2',self.view_variables))
1597| self.mbarView.add_separator()
1598| self.mbarView.add_command(**kw('Operators' ,0,'F4',self.view_operators))
1599|
1600|
1601| self.mbarHelp = tk.Menu(self.mbar, name='helpMenu', tearoff=0, postcommand=app_test_proxy('Menu.Help'))
1602| self.mbarHelp.add_command(**kw('About', 0, 'F12', self.help_about))
1603|
1604|
1605| self.mbar.add_cascade(label='File', menu=self.mbarFile, underline=0)
1606| self.mbar.add_cascade(label='Edit', menu=self.mbarEdit, underline=0)
1607| self.mbar.add_cascade(label='View', menu=self.mbarView, underline=0)
1608| self.mbar.add_cascade(label='Help', menu=self.mbarHelp, underline=0)
1609|
1610|
1611| self.root['menu'] = self.mbar
1612|
1613|
1614|
1615| def do_main (**kwargs):
1616| '''CMND: Run the GUI App.'''
1617| Log.info(f'main:: {str(list(kwargs.keys()))}')
1618| Log.info()
1619| flag = KWARG('flag', 1, int, kwargs)
1620|
1621|
1622| app = Application(**kwargs)
1623| bag['app'] = app
1624|
1625|
1626| if flag:
1627| app.root.mainloop()
1628|
1629| Log.info()
1630| return 'Done'
1631|
1632|
1633| def do_test (**kwargs):
1634| '''CMND: Do a test.'''
1635| fpath = KWARG('fpath', BasePath, str, kwargs)
1636| fname = KWARG('fname', 'test.out', str, kwargs)
1637| Log.info(f'test:: {str(list(kwargs.keys()))}' )
1638| Log.debug(f'{fpath=}')
1639| Log.debug(f'{fname=}')
1640| Log.info()
1641| source = """\
1641| func foobar
1641| sqrt add
1641| square X
1641| square Y
1641| end
1641| set X 3
1641| set Y 4
1641| set length call foobar end
1641| """
1642| tokens = Calculator.parse_text(source)
1643| Log.info('Tokens:')
1644| for ix,tok in enumerate(tokens, start=1):
1645| Log.info(f'{ix}: {tok}')
1646| Log.info()
1647|
1648| calc = Calculator(tokens)
1649| Log.info()
1650|
1651| Log.info('Results:')
1652| for ix,result in enumerate(calc.results):
1653| Log.info(f'{ix}: {result}')
1654| Log.info()
1655|
1656| Log.info('Variables:')
1657| for name in calc.variables:
1658| Log.info(f'{name}: {calc.variables[name]}')
1659| Log.info()
1660|
1661| return 'Done'
1662|
1663| def dispatch (cmd, **kwargs):
1664| '''Dispatch to a module function based on CMD.'''
1665| Log.info(f'CMD: {cmd}')
1666| for kw in kwargs:
1667| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
1668| Log.info()
1669| if cmd == 'main': return do_main(**kwargs)
1670| if cmd == 'test': return do_test(**kwargs)
1671| return 'Nothing to do!'
1672|
1673| if __name__ == '__main__':
1674| print(f'autorun: {argv[0]}')
1675| Log.start(path.join(BasePath,'tk-calc.log'))
1676| Log.level(trace())
1677| Log.info(argv[0])
1678| Log.info()
1679| cmd = argv[1] if 1 < len(argv) else CMND
1680| kwargs = ARGS
1681| for a in argv[2:]:
1682| nv = a.split('=', 1)
1683| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
1684| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
1685| try:
1686| print(f'CMD: {cmd}')
1687| print()
1688| obj = dispatch(cmd, **kwargs)
1689| if 'app' in bag: app=bag['app']
1690| print()
1691| print(obj)
1692| Log.info()
1693| Log.info(obj)
1694| except:
1695| etype, evalue, tb = exc_info()
1696| ts = extract_tb(tb)
1697| Log.error()
1698| Log.error(f'{etype.__name__}: {evalue!s}')
1699| Log.error()
1700| for t in ts[-5:]:
1701| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
1702| Log.error(f' {t[3]}')
1703| Log.error()
1704| raise
1705| finally:
1706| Log.end()
1707|
1708| '''eof'''
1709|