Last active
April 22, 2019 20:19
-
-
Save phunanon/6c9cc8906552e2a5913d99990396c393 to your computer and use it in GitHub Desktop.
Simple GTK+ Python calculator, traditional one-num-carry, extensible operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import gi | |
gi.require_version('Gtk', '3.0') | |
from gi.repository import Gtk | |
class Calculator: | |
def __init__ (self): | |
self.carry = 0 | |
self.ops = { | |
'=': (lambda x, y: self.carry), | |
'+': (lambda x, y: x + y), | |
'-': (lambda x, y: x - y), | |
'*': (lambda x, y: x * y), | |
'/': (lambda x, y: x / y), | |
'%': (lambda x, y: x % y), | |
'^': (lambda x, y: x ** y) } | |
self.nextOp = self.ops['+'] | |
def DoOp (self, func, entry): | |
self.carry = self.nextOp(self.carry, entry) | |
self.nextOp = func | |
return self.carry | |
class MyWindow (Gtk.Window): | |
def __init__ (self): | |
super().__init__() | |
self.calculator = Calculator() | |
self.clearCarry = False | |
self.init_ui() | |
def init_ui (self): | |
self.set_title("GTK+ Calc") | |
self.set_default_size(128, 148) | |
self.set_border_width(16) | |
self.set_resizable(False) | |
self.connect("destroy", Gtk.main_quit) | |
grid = Gtk.Grid() | |
grid.set_row_spacing(4) | |
grid.set_column_spacing(4) | |
self.add(grid) | |
entry = Gtk.Label() | |
entry.set_selectable(True) | |
entry.set_halign(Gtk.Align.START) | |
grid.attach(entry, 0, 0, 12, 1) | |
gridAdder = lambda btn, x, y: grid.attach(btn, x % 10, y + (x / 10), 2, 1) | |
# Add operator buttons row | |
x = 0 | |
for op, func in self.calculator.ops.items(): | |
btn = Gtk.Button(label=op) | |
btn.connect("clicked", lambda widget, func=func: self.BtnOpPress(entry, func)) | |
gridAdder(btn, x, 1) | |
x = x + 2 | |
# Add number buttons rows | |
x = 0 | |
for n in list(range(1, 10)) + [0, '.']: | |
btn = Gtk.Button(label=n) | |
btn.connect("clicked", lambda widget, n=n: self.BtnEntryPress(entry, n)) | |
gridAdder(btn, x, 3) | |
x = x + 2 | |
def BtnOpPress (self, entry, func): | |
entry.set_text(str(self.calculator.DoOp(func, float(entry.get_text())))) | |
self.clearCarry = True | |
def BtnEntryPress (self, entry, num): | |
if self.clearCarry: | |
self.clearCarry = False | |
entry.set_text(str(num)) | |
else: | |
entry.set_text(entry.get_text() + str(num)) | |
win = MyWindow() | |
win.show_all() | |
Gtk.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment