#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2020-2025 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # units.pyw # # This is a GUI which lets you run python expression to calculate numbers, # which are then used to convert from/to many common measurement units. # # Updates happen automatically, each time the main input changes. import math from math import \ acos, acosh, asin, asinh, atan, atan2, atanh, ceil, comb, \ copysign, cos, cosh, degrees, dist, e, erf, erfc, exp, expm1, \ fabs, factorial, floor, fmod, frexp, fsum, gamma, gcd, hypot, inf, \ isclose, isfinite, isinf, isnan, isqrt, lcm, ldexp, lgamma, log, \ log10, log1p, log2, modf, nan, nextafter, perm, pi, pow, prod, \ radians, remainder, sin, sinh, sqrt, tan, tanh, tau, trunc, ulp try: from math import cbrt, exp2 except Exception: pass from random import \ betavariate, choice, choices, expovariate, gammavariate, gauss, \ getrandbits, getstate, lognormvariate, normalvariate, paretovariate, \ randbytes, randint, random, randrange, sample, seed, setstate, \ shuffle, triangular, uniform, vonmisesvariate, weibullvariate from statistics import \ bisect_left, bisect_right, fmean, \ geometric_mean, harmonic_mean, mean, median, \ median_grouped, median_high, median_low, mode, multimode, pstdev, \ pvariance, quantiles, stdev, variance try: from statistics import \ correlation, covariance, linear_regression, mul, reduce except Exception: pass from tkinter import Tk, Entry, Label, TOP, BOTTOM, LEFT, Event from typing import List, Tuple, Union, Any # some occasionally-useful values kb = 1024 mb = 1024 * kb gb = 1024 * mb tb = 1024 * gb pb = 1024 * tb mole = 602214076000000000000000 mol = mole def check_shortcuts(event: Any) -> None: char: str = event.char if char == '': return # copy formula and result to clipboard when enter is pressed if ord(char) == 13: copy(output['text']) # quit when esc key is pressed if ord(char) == 27: win.quit() def update_result(event: Event) -> None: try: expr = input.get() if expr == '': return # square brackets are easier to type and are valid math expr = expr.replace('[', '(').replace(']', ')') output['text'] = convert(eval(expr)) except Exception as e: output['text'] = e def copy(s: str) -> None: # tkinter's clipboard functionality isn't working from subprocess import run for p in ['xclip -i', 'wclip -i', 'clip.exe', 'pbcopy']: try: run(p, input=s, text=True) # copy successful, so return return except Exception: pass def convert(x: float) -> str: t = [] for e in table: if e is None: t.append('') else: y = e[1] * x + e[2] t.append('{:,} {:<3} = {:,.4f} {}'.format(x, e[0], y, e[3])) return '\n'.join(t) # unit conversion table table: List[Union[Tuple[str, float, float, str], None]] = [ # from, multiplier, offset, to # none values mark where to put empty lines in the output ('ft', 0.3048, 0, 'm'), ('m', 3.28084, 0, 'ft'), ('in', 2.54, 0, 'cm'), ('cm', 0.393701, 0, 'in'), ('mi', 1.60934, 0, 'km'), ('km', 0.621371, 0, 'mi'), ('yd', 0.9144, 0, 'm'), ('m', 1.09361, 0, 'yd'), None, ('f', 5/9, -32*5/9, 'c'), ('c', 9/5, 32, 'f'), None, ('lb', 0.453592, 0, 'kg'), ('kg', 2.20462, 0, 'lb'), ('oz', 28.3495, 0, 'g'), ('g', 0.035274, 0, 'oz'), None, ('gal', 3.78541, 0, 'l'), ('l', 0.264172, 0, 'gal'), None, ('in2', 6.4516, 0, 'cm2'), ('cm2', 0.15500031, 0, 'in2'), ('ft2', 0.092903, 0, 'm2'), ('m2', 10.7639, 0, 'ft2'), ('mi2', 2.58999, 0, 'km2'), ('km2', 0.386102, 0, 'mi2'), ('ac', 0.00404686, 0, 'km2'), ('km2', 247.105, 0, 'ac'), ] win = Tk() win.title('Unit-conversion Calculator') input = Entry(font=20, width=35) input.pack(side=TOP, padx=5) input.bind('', check_shortcuts) input.bind('', update_result) input.focus() font = ('Lucida Console', 12) output = Label(text='esc\tquits\nenter\tcopies to clipboard', font=font) output.config(justify=LEFT) output.pack(side=BOTTOM, padx=10, pady=5) win.mainloop()