# How to make a simple Calculator

## A little bit of history

Abacus is a Latin word that has its origins in the Greek words abax or abakon (meaning “table” or “tablet”) which in turn, possibly originated from the Semitic word abq, meaning “sand”. The abacus is one of many types of counting devices which are used to count large numbers. Why does the abacus exist?

It is difficult to imagine counting without numbers, but there was a time when written numbers did not exist. The earliest counting device was the human hand and its fingers, capable of counting up to 10 things; toes were also used to count in tropical cultures. Then, as even larger quantities (greater than ten fingers and toes could represent) were counted, various natural items like pebbles, sea shells and twigs were used to help keep count.

Merchants who traded goods needed a way to keep count (inventory) of the goods they bought and sold. Various portable counting devices were invented to keep tallies. The abacus is one of many counting devices invented to help count large numbers. When the Hindu-Arabic number system came into use, abaci were adapted to use place-value counting.

Abaci evolved into electro-mechanical calculators, pocket slide-rules, electronic calculators and now abstract representations of calculators or simulations on smartphones. Photo by Crissy Jarvis on Unsplash

## What is the difference between a counting board and an abacus?

It is important to distinguish the early abacuses (or abaci) known as counting boards from the modern abaci. The counting board is a piece of wood, stone or metal with carved grooves or painted lines between which beads, pebbles or metal discs were moved. The abacus is a device, usually of wood (romans made them out of metal and they are made of plastic in modern times), having a frame that holds rods with freely-sliding beads mounted on them.

Both the abacus and the counting board are mechanical aids used for counting; they are not calculators in the sense we use the word today. The person operating the abacus performs calculations in their head and uses the abacus as a physical aid to keep track of the sums, the carrys, etc.

Today we can build our own calculator using python and the Tkinter and Math libraries

## Import libraries

`from tkinter import *import tkinter as tkimport math# globally declare the expression variable expression = ""inverted = False`

## Create functions

`# Function to update expressiom # in the text entry box # point out the global expression variable def press(num):    # point out the global expression variable     global expression    # concatenation of string    expression = expression + str(num)    # update the expression by using set method     equation.set(expression)# Function to evaluate the final expressiondef equalpress():    try:    # Try and except statement is used     # for handling the errors like zero     # division error etc.       # Put that code inside the try block     # which may generate the error         global expression        # eval function evaluate the expression         # and str function convert the result         # into string         total = eval(expression)        equation.set(total)                # initialze the expression variable         # by empty string         expression = ""    # if error is generate then handle     # by the except block     except:        equation.set(" Error ")        expression = ""# Function to clear the contents # of text entry box def clear():    global expression    expression = ""    equation.set("")    return# Function to a square root of a number def sqrt():    global expression    expression = math.sqrt(float(expression))    equation.set(float(expression))    expression = str(expression)# Function Sine, Cosine and Tangent (often shortened to sin, cos and tan) # are each a ratio of sides of a right angled triangle def sin():    global expression    expression = float(expression)    expression = round(math.sin(math.radians(expression)), 5)    equation.set(float(expression))    expression = str(expression)def cos():    global expression    expression = float(expression)    expression = round(math.cos(math.radians(expression)), 5)    equation.set(float(expression))    expression = str(expression)def tan():    global expression    expression = float(expression)    expression = round(math.tan(math.radians(expression)), 5)    equation.set(float(expression))    expression = str(expression)# Now, functions of Inverse trigonometric functionsdef asin():    global expression    expression = float(expression)    expression = round((math.asin(expression)) * (180 / math.pi), 3)    equation.set(float(expression))    expression = str(expression)def acos():    global expression    expression = float(expression)    expression = round((math.acos(expression)) * (180 / math.pi), 3)    equation.set(float(expression))    expression = str(expression)def atan():    global expression    expression = float(expression)    expression = round((math.atan(expression)) * (180 / math.pi), 3)    equation.set(float(expression))    expression = str(expression)def retrieve_input():    try:        global expression        inputValue1 = InputA.get()        inputValue2 = InputB.get()        inputValue1 = float(inputValue1)        inputValue2 = float(inputValue2)        expression = float(math.sqrt(inputValue1 * inputValue1 + inputValue2 * inputValue2))        equation.set(float(expression))        expression = str(expression)    except:        equation.set(" Error ")        expression = ""def inv():    global inverted    inverted = not inverted`

## Let´s create the widget

We are going to us Tkinter.

Tkinter is a binding of the graphic library Tcl/Tk for the Python programming language. It is considered a standard for the graphical user interface (GUI) for Python and is the one that comes by default with the installation for Microsoft Windows.

Today there are other alternatives available such as wxPython, PyQt or PySide and PyGTK that meet all visual component standards.

`# Driver code if __name__ == "__main__":    # create a GUI window     gui = Tk()    # set the background colour of GUI window     gui.configure(background="black")    # set the title of GUI window    gui.title("Calculator")    # set the configuration of GUI window     gui.geometry("520x240")    # StringVar() is the variable class     # we create an instance of this class     equation = StringVar()    A = StringVar()    B = StringVar()    # create the text entry box for     # showing the expression .     expression_field = Entry(gui, textvariable=equation)      # grid method is used for placing     # the widgets at respective positions     # in table like structure .     expression_field.grid(columnspan=45, ipadx=200)    equation.set('Enter Your Expression')    lbl1 = Label(gui, text="Enter A value:", font=("Arial Bold", 10),    bg="white")    lbl1.grid(column=0, row=13, sticky=W)    InputA = Entry(gui, width=12, textvariable=A)    InputA.grid(column=1, row=13)    lbl2 = Label(gui, text="Enter B value:", font=("Arial Bold", 10),    bg="white")    lbl2.grid(column=0, row=14, sticky=W)    InputB = Entry(gui, width=12, textvariable=B)    InputB.grid(column=1, row=14)      # create a Buttons and place at a particular     # location inside the root window .     # when user press the button, the command or     # function affiliated to that button is executed .     buttonab = Button(gui, text=' √(A^2 + B^2) ', fg='black', bg='white',    command=lambda: retrieve_input(), height=1,width=11)    buttonab.grid(row=15, column=0, sticky=W + E)    button1 = Button(gui, text=' 1 ', fg='black', bg='white',    command=lambda: press(1), height=1, width=7)    button1.grid(row=4, column=0)    button2 = Button(gui, text=' 2 ', fg='black', bg='white',    command=lambda: press(2), height=1, width=7)    button2.grid(row=4, column=1)    button3 = Button(gui, text=' 3 ', fg='black', bg='white',    command=lambda:    press(3), height=1, width=7)    button3.grid(row=4, column=2)    button4 = Button(gui, text=' 4 ', fg='black', bg='white',    command=lambda: press(4), height=1, width=7)    button4.grid(row=3, column=0)    button5 = Button(gui, text=' 5 ', fg='black', bg='white',    command=lambda: press(5), height=1, width=7)    button5.grid(row=3, column=1)    button6 = Button(gui, text=' 6 ', fg='black', bg='white',    command=lambda: press(6), height=1, width=7)    button6.grid(row=3, column=2)    button7 = Button(gui, text=' 7 ', fg='black', bg='white',    command=lambda: press(7), height=1, width=7)    button7.grid(row=2, column=0)    button8 = Button(gui, text=' 8 ', fg='black', bg='white',    command=lambda: press(8), height=1, width=7)    button8.grid(row=2, column=1)    button9 = Button(gui, text=' 9 ', fg='black', bg='white',    command=lambda: press(9), height=1, width=7)    button9.grid(row=2, column=2)    button0 = Button(gui, text=' 0 ', fg='black', bg='white',    command=lambda: press(0), height=1, width=7)    button0.grid(row=5, column=1)    plus = Button(gui, text=' + ', fg='black', bg='yellow',    command=lambda: press("+"), height=1, width=7)    plus.grid(row=2, column=3)    minus = Button(gui, text=' - ', fg='black', bg='yellow',    command=lambda:    press("-"), height=1, width=7)    minus.grid(row=3, column=3)    multiply = Button(gui, text=' * ', fg='black', bg='yellow',    command=lambda: press("*"), height=1, width=7)    multiply.grid(row=4, column=3)    divide = Button(gui, text=' / ', fg='black', bg='yellow',    command=lambda: press("/"), height=1, width=7)    divide.grid(row=5, column=3)    equal = Button(gui, text=' = ', fg='black', bg='orange',    command=equalpress, height=1, width=7)    equal.grid(row=5, column=2)    clear = Button(gui, text='Clear', fg='black', bg='orange', command=clear,    height=1, width=7)    clear.grid(row=2, column=6)    sqrt = Button(gui, text=' √ ', fg='black', bg='yellow', command=sqrt,    height=1, width=7)    sqrt.grid(row=3, column=6)    dec = Button(gui, text=' . ', fg='black', bg='orange', command=lambda:    press("."), height=1, width=7)    dec.grid(row=5, column=0)    sin = Button(gui, text='sin', fg='black', bg='red',    command=sin, height=1, width=7)    sin.grid(row=2, column=4)    cos = Button(gui, text='cos', fg='black', bg='red',    command=cos, height=1, width=7)    cos.grid(row=3, column=4)    tan = Button(gui, text='tan', fg='black', bg='red',    command=tan, height=1, width=7)    tan.grid(row=4, column=4)    inv = Button(gui, text='INV', fg='black', bg='red',    command=inv, height=1, width=7)    inv.grid(row=6, column=4)    if not inverted:        sin = Button(gui, text='sin', fg='black', bg='red',         command=sin,         height=1, width=7)        sin.grid(row=2, column=4)        cos = Button(gui, text='cos', fg='black', bg='red',         command=cos,         height=1, width=7)        cos.grid(row=3, column=4)        tan = Button(gui, text='tan', fg='black', bg='red',         command=tan,         height=1, width=7)        tan.grid(row=4, column=4)    else:        sin = Button(gui, text='sin^-1', fg='black', bg='red',         command=asin, height=1, width=7)        sin.grid(row=2, column=4)        cos = Button(gui, text='cos-1', fg='black', bg='red',         command=acos, height=1, width=7)        cos.grid(row=3, column=4)        tan = Button(gui, text='tan-1', fg='black', bg='red',         command=atan, height=1, width=7)        tan.grid(row=4, column=4)# start the GUI gui.mainloop()`

Now all toghether in a calculator.py file from tkinter import * import tkinter as tk import math

# point out the global expression variable

def press(num): # point out the global expression variable global expression # concatenation of string expression = expression + str(num) # update the expression by using set method equation.set(expression)

# Function to evaluate the final expression

def equalpress(): try: # Try and except statement is used # for handling the errors like zero # division error etc.

`# Put that code inside the try block # which may generate the error     global expression    # eval function evaluate the expression     # and str function convert the result     # into string     total = eval(expression)    equation.set(total)        # initialze the expression variable     # by empty string     expression = ""# if error is generate then handle # by the except block except:    equation.set(" Error ")    expression = ""`

# of text entry box

def clear(): global expression expression = “” equation.set(“”) return

# Function to a square root of a number

def sqrt(): global expression expression = math.sqrt(float(expression)) equation.set(float(expression)) expression = str(expression)

# are each a ratio of sides of a right angled triangle

def sin(): global expression expression = float(expression) expression = round(math.sin(math.radians(expression)), 5) equation.set(float(expression)) expression = str(expression)

def cos(): global expression expression = float(expression) expression = round(math.cos(math.radians(expression)), 5) equation.set(float(expression)) expression = str(expression)

def tan(): global expression expression = float(expression) expression = round(math.tan(math.radians(expression)), 5) equation.set(float(expression)) expression = str(expression)

# Now, functions of Inverse trigonometric functions

def asin(): global expression expression = float(expression) expression = round((math.asin(expression)) * (180 / math.pi), 3) equation.set(float(expression)) expression = str(expression)

def acos(): global expression expression = float(expression) expression = round((math.acos(expression)) * (180 / math.pi), 3) equation.set(float(expression)) expression = str(expression)

def atan(): global expression expression = float(expression) expression = round((math.atan(expression)) * (180 / math.pi), 3) equation.set(float(expression)) expression = str(expression)

def retrieve_input(): try: global expression inputValue1 = InputA.get() inputValue2 = InputB.get() inputValue1 = float(inputValue1) inputValue2 = float(inputValue2)

`expression = float(math.sqrt(inputValue1 * inputValue1 + inputValue2 * inputValue2))    equation.set(float(expression))    expression = str(expression)except:    equation.set(" Error ")    expression = ""`

def inv(): global inverted inverted = not inverted

# Driver code

if name == “main”: # create a GUI window gui = Tk() # set the background colour of GUI window gui.configure(background=”black”) # set the title of GUI window gui.title(“Calculator”) # set the configuration of GUI window gui.geometry(“520x240”) # StringVar() is the variable class # we create an instance of this class equation = StringVar() A = StringVar() B = StringVar()

`# create the text entry box for # showing the expression . expression_field = Entry(gui, textvariable=equation)# grid method is used for placing # the widgets at respective positions # in table like structure . expression_field.grid(columnspan=45, ipadx=200)equation.set('Enter Your Expression')lbl1 = Label(gui, text="Enter A value:", font=("Arial Bold", 10),bg="white")lbl1.grid(column=0, row=13, sticky=W)InputA = Entry(gui, width=12, textvariable=A)InputA.grid(column=1, row=13)lbl2 = Label(gui, text="Enter B value:", font=("Arial Bold", 10),bg="white")lbl2.grid(column=0, row=14, sticky=W)InputB = Entry(gui, width=12, textvariable=B)InputB.grid(column=1, row=14)# create a Buttons and place at a particular # location inside the root window . # when user press the button, the command or # function affiliated to that button is executed . buttonab = Button(gui, text=' √(A^2 + B^2) ', fg='black', bg='white',command=lambda: retrieve_input(), height=1,width=11)buttonab.grid(row=15, column=0, sticky=W + E)button1 = Button(gui, text=' 1 ', fg='black', bg='white',command=lambda: press(1), height=1, width=7)button1.grid(row=4, column=0)button2 = Button(gui, text=' 2 ', fg='black', bg='white',command=lambda: press(2), height=1, width=7)button2.grid(row=4, column=1)button3 = Button(gui, text=' 3 ', fg='black', bg='white',command=lambda:press(3), height=1, width=7)button3.grid(row=4, column=2)button4 = Button(gui, text=' 4 ', fg='black', bg='white',command=lambda: press(4), height=1, width=7)button4.grid(row=3, column=0)button5 = Button(gui, text=' 5 ', fg='black', bg='white',command=lambda: press(5), height=1, width=7)button5.grid(row=3, column=1)button6 = Button(gui, text=' 6 ', fg='black', bg='white',command=lambda: press(6), height=1, width=7)button6.grid(row=3, column=2)button7 = Button(gui, text=' 7 ', fg='black', bg='white',command=lambda: press(7), height=1, width=7)button7.grid(row=2, column=0)button8 = Button(gui, text=' 8 ', fg='black', bg='white',command=lambda: press(8), height=1, width=7)button8.grid(row=2, column=1)button9 = Button(gui, text=' 9 ', fg='black', bg='white',command=lambda: press(9), height=1, width=7)button9.grid(row=2, column=2)button0 = Button(gui, text=' 0 ', fg='black', bg='white',command=lambda: press(0), height=1, width=7)button0.grid(row=5, column=1)plus = Button(gui, text=' + ', fg='black', bg='yellow',command=lambda: press("+"), height=1, width=7)plus.grid(row=2, column=3)minus = Button(gui, text=' - ', fg='black', bg='yellow',command=lambda:press("-"), height=1, width=7)minus.grid(row=3, column=3)multiply = Button(gui, text=' * ', fg='black', bg='yellow',command=lambda: press("*"), height=1, width=7)multiply.grid(row=4, column=3)divide = Button(gui, text=' / ', fg='black', bg='yellow',command=lambda: press("/"), height=1, width=7)divide.grid(row=5, column=3)equal = Button(gui, text=' = ', fg='black', bg='orange',command=equalpress, height=1, width=7)equal.grid(row=5, column=2)clear = Button(gui, text='Clear', fg='black', bg='orange', command=clear,height=1, width=7)clear.grid(row=2, column=6)sqrt = Button(gui, text=' √ ', fg='black', bg='yellow', command=sqrt,height=1, width=7)sqrt.grid(row=3, column=6)dec = Button(gui, text=' . ', fg='black', bg='orange', command=lambda:press("."), height=1, width=7)dec.grid(row=5, column=0)sin = Button(gui, text='sin', fg='black', bg='red',command=sin, height=1, width=7)sin.grid(row=2, column=4)cos = Button(gui, text='cos', fg='black', bg='red',command=cos, height=1, width=7)cos.grid(row=3, column=4)tan = Button(gui, text='tan', fg='black', bg='red',command=tan, height=1, width=7)tan.grid(row=4, column=4)inv = Button(gui, text='INV', fg='black', bg='red',command=inv, height=1, width=7)inv.grid(row=6, column=4)if not inverted:    sin = Button(gui, text='sin', fg='black', bg='red',     command=sin,     height=1, width=7)    sin.grid(row=2, column=4)    cos = Button(gui, text='cos', fg='black', bg='red',     command=cos,     height=1, width=7)    cos.grid(row=3, column=4)    tan = Button(gui, text='tan', fg='black', bg='red',     command=tan,     height=1, width=7)    tan.grid(row=4, column=4)else:    sin = Button(gui, text='sin^-1', fg='black', bg='red',     command=asin, height=1, width=7)    sin.grid(row=2, column=4)    cos = Button(gui, text='cos-1', fg='black', bg='red',     command=acos, height=1, width=7)    cos.grid(row=3, column=4)    tan = Button(gui, text='tan-1', fg='black', bg='red',     command=atan, height=1, width=7)    tan.grid(row=4, column=4)`

# start the GUI

gui.mainloop()

`! python calculadora.py`

## Conclusion

For beginner student is not easy built a calculator widget with tkinter. I recommended go to the library documentation.

I hope you like it.

No matter what books or blogs or courses or videos one learns from, when it comes to implementation everything can look like “Outside the Curriculum”.

The best way to learn is by doing! The best way to learn is by teaching what you have learned!

## Never give up!

See you on Linkedin!

## References:

`https://www.geeksforgeeks.org/python-simple-gui-calculator-using-tkinter/https://es.wikipedia.org/wiki/Tkinter`

Master in Data Science. Passionate about learning new skills. Former branch risk analyst. https://www.linkedin.com/in/oscar-rojo-martin/. www.oscarrojo.es

## More from Oscar Rojo

Master in Data Science. Passionate about learning new skills. Former branch risk analyst. https://www.linkedin.com/in/oscar-rojo-martin/. www.oscarrojo.es