Writing a calculator program in Python

Illustration of calculator display

Command buttons

# abstract class defines command interface
class DButton (Button):
def __init__(self, master, **kwargs):
super().__init__(master, command=self.comd, **kwargs)
def comd(self):
class NumButton(DButton):
def __init__(self, master, med, **kwargs):
super().__init__(master, width=2, fg='white',
bg="#aaa", **kwargs)
butnfont = tkFont.Font(family='Helvetica',
size=16, weight='bold')
self['font'] = butnfont
self.med= med # save copy of Mediator
def comd(self):
self.med.numClick(self['text']) # gets number from label
# Any number is clicked
def numClick(self, text):
if self.first: # if first char clear the zero
self.setlabelText(" ") # leading space
self.first = False
st = self.getLabelText() + text
but = NumButton(root, med, text='7')
but.grid(row=2, column=0, padx=1, pady=1)
but = NumButton(root, med, text='8')
but.grid(row=2, column=1, padx=1, pady=1)
but = NumButton(root, med, text='9')
but.grid(row=2, column=2, padx=1, pady=1)
How the buttons communicate with the Mediator

Using a Dictionary to choose operations

funcs = {"+": self.addfun,
"-": self.subfun,
"*": self.multfun,
"/": self.divfun }
func = funcs.get(sign) # will be one of four symbols
sum = func() # execute that function





is the author of “Python Programming with Design Patterns” and 20 previous books.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

EFK Stack on Kubernetes

Subirority Complex — Issue #15

7 minute guide on implementing ConstraintLayout in Android

Validating Requests with Laravel Validate

How to setup ROS2 Fast-DDS Discovery Server

Flutter: Best Practices — 1

Serverless Operations 101

FlexBuffers for Unity3D

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
James Cooper

James Cooper

is the author of “Python Programming with Design Patterns” and 20 previous books.

More from Medium

Python Programming: The Pros and Cons of Python

How to install GDAL in a Python virtual environment

Do you know about Python Programming? Jason Sindelar Explained.

Jason Sindelar Python Quote

Python Operators