Simple Calculator Program in Python
In this post, you will learn how to develop a simple calculator program using the Python programming language. By using this, you can develop a simple calculator that display the different arithmetical operations, i.e., addition, subtraction, multiplication and division.
Algorithm of Simple Calculator
Step 1: Declare local variables
Step 2: Enter any operator at runtime
Step 3: Enter any two integer values at runtime
Step 4: Enter the Choice
Step 5: Apply switch case to select the operator:
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default: printf("\n Invalid Operator ");
Step 5: Print the result
Tkinter is a standard cross-platform package for creating GUIs. It is also called Tk interface. It is an original GUI library for Tcl (Tool Command Language). Tkinter comes pre-installed with Python. Tkinter is rich in widgets, like radiobutton, checkbutton, menu, frame, canvas, and much more. Here, we have used this for developing a simple calculator program.
We have broken the code into multiple steps that are easy to understand for you.
STEP 1
We start by defining functions to make the creation of frame and button widgets more minimal. These functions utilize the pack geometry and utilize more commonly used values for widget behaviour. It is always a good idea to gather regular code in common functions since it makes readability and maintenance much easier.
def frame(root, side):
window = Frame(root)
window.pack(side=side, expand=YES, fill=BOTH)
return window
def button(root, side, text, command=None):
window = Button(root, text=text, command=command, background = 'lightgray')
window.pack(side=side, expand=YES, fill=BOTH)
return window
STEP 2
We call the Frame constructor to make the toplevel shell and an enclosing frame. Then, we set titles for the window and symbol.
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('Simple Calculator')
self.master.iconname("calculator")
self.master.geometry('300x250')
display = StringVar()
STEP 3
Next, we make the display at the top of the calculator and characterise a Tkinter variable which provides access to the widget's contents.
display = StringVar()
Entry(self, relief=SUNKEN,
textvariable=display, background = 'lightyellow').pack(side=TOP, expand=YES,
fill=BOTH)
STEP 4
Note that character strings are arrangements of characters in Python, so that each of the subsequences is really an array of characters over which we can repeat.
for key in ("123", "456", "789", "-0."):
keyFrame = frame(self, TOP)
for char in key:
We use the convenience function to create a button, passing the frame, pack option, label, and callback.
button(keyFrame, LEFT, char,
lambda w=display, s=' %s '%char: w.set(w.get()+s))
STEP 5
The key has an alternate binding to the other buttons since it calls the calc method when the left mouse button is delivered.
btn = button(x, LEFT, char)
btn.bind('',
lambda e, s=self, w=display: s.calc(w), '+')
STEP 6
The calc method endeavours to assess the string contained in the display, and afterward it replaces the contents with the calculated value or an ERROR message:
display.set(eval(display.get()))
Complete Code: Simple Calculator Program in Python
Here, we have merged the above code for a simple calculator program in Python.
from tkinter import *
def frame(root, side):
window = Frame(root)
window.pack(side=side, expand=YES, fill=BOTH)
return window
def button(root, side, text, command=None):
window = Button(root, text=text, command=command, background = 'lightgray')
window.pack(side=side, expand=YES, fill=BOTH)
return window
class SimpleCalculator(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('Simple Calculator')
self.master.iconname("calculator")
self.master.geometry('300x250')
display = StringVar()
Entry(self, relief=SUNKEN,
textvariable=display, background = 'lightyellow').pack(side=TOP, expand=YES,
fill=BOTH)
for key in ("123", "456", "789", "-0."):
keyFrame = frame(self, TOP)
for char in key:
button(keyFrame, LEFT, char,
lambda w=display, s=' %s '%char: w.set(w.get()+s))
x = frame(self, TOP)
for char in "+-*/=":
if char == '=':
btn = button(x, LEFT, char)
btn.bind('',
lambda e, s=self, w=display: s.calc(w), '+')
else:
btn = button(x, LEFT, char,
lambda w=display, c=char: w.set(w.get()+' '+c+' '))
clearF = frame(self, BOTTOM)
button(clearF, LEFT, 'Clr', lambda w=display: w.set(''))
def calc(self, display):
try:
display.set(eval(display.get()))
except ValueError:
display.set("ERROR")
if __name__ == '__main__':
SimpleCalculator().mainloop()
Sample output of the above program -
Related Articles
Greatest common divisor Python recursive
Python String isalpha() Method
Program to print ASCII Value of a character
Python heap implementation
Python program to sort words in alphabetical order
*args and **kwargs in Python
Bouncing ball game code in Python
Printing Simple Diamond Pattern in Python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module
Text Detection and Extraction using OpenCV and OCR
Python Random shuffle() Method
Fibonacci Series In Python | Python Program To Print
File Handling in Python
Python - XML to JSON
Python XML to Dictionary
Serialize Python dictionary to XML