How to make a calculator in Python + Python Tkinter Calculator

In this Python tutorial, we will make a calculator in python, which can add, subtract, divide, and multiply depending upon the user-entered input.

Also, we will discuss how to create a Python Calculator using Tkinter.

Make a calculator in Python

Let us see how we can create a calculator in Python using functions.

As you can see that we have created a simple calculator in Python, which can perform different arithmetical operations like add, subtract, multiply, and divide. The user-defined function is add(), subtract(), multiply() and divide() will evaluate the respective operation and display the output.

Example:

def add(x,y):
    return x + y
def subtract(x,y):
    return x - y
def multiply(x,y):
    return x * y
def divide(x,y):
    return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
    choice = input("Enter your choice(1/2/3/4): ")
    if choice in ('1', '2', '3', '4'):
        number1 = float(input("Enter first number: "))
        number2 = float(input("Enter second number: "))
        if choice == '1':
           print(number1, "+", number2, "=", add(number1, number2))
        elif choice == '2':
           print(number1, "-", number2, "=", subtract(number1, number2))
        elif choice == '3':
           print(number1, "*", number2, "=", multiply(number1, number2))
        elif choice == '4':
           print(number1, "/", number2, "=", divide(number1, number2))
        break
     else:
         print("Entered input is invalid")

You can refer to the below screenshot to make a calculator in Python.

How to make a calculator in Python
How to make a calculator in Python

Output:
Here, we ask the user to choose an operation of their choice. If the option is 1,2,3, and 4 then it will be valid else it will display “Invalid input”. If the option is valid then we have to enter the two numbers and according to the user entered choice, it will perform the operation.

calculator in Python
calculator in Python

Calculator in Python using class

Let’s see step by step how we can create a class that will perform basic calculator operations.

  • To make a calculator using class. Classes are required to create an object. Classes make the code more efficient and simple enough to understand.
  • First, we will create a class calculator and all the function is defined like addition, subtraction, multiplication, and division.
  • Self is used while calling the function using obj1.function(). Here, the function will call itself.
  • Now, we will take the input from the user and the object is created.
  • And at last, create the user chooses to perform the operation they need and print the value in the output.

Example:

class calculator:
    def addition(self):
        print(x + y)
    def subtraction(self):
        print(x - y)
    def multiplication(self):
        print(x * y)
    def division(self):
        print(x / y)
x = int(input("Enter first number:"))
y = int(input("Enter second number:"))
obj1 = calculator()
choice = 1
while choice !=0:
    print("1. ADDITION")
    print("2. SUBTRACTION")
    print("3. MULTIPLICATION")
    print("4. DIVISION")
    choice = int(input("Enter your choice:"))
    if choice == 1:
        print(obj1.addition())
    elif choice == 2:
        print(obj1.subtraction())
    elif choice == 3:
        print(obj1.multiplication())
    elif choice == 4:
        print(obj1.division())
    else:
        print("Invalid choice")

Now, you can see code with the output.

Calculator in python using class
Calculator in python using class

Output:

Calculator in python using class
Calculator in python using class

Calculator in Python without function

We have created a simple calculator in Python without a function that can perform different arithmetical operations like add, subtract, multiply, and divide.

READ:  How to use Python Scipy Differential Evolution

Example:

first_val = input("Enter 1st number: ")
first_val = int(first_val)
cal = input("Enter operator: ")
second_val = input("Enter 2nd number: ")
second_val = int(second_val)
if cal == "+":
    print(first_val + second_val)
elif cal == "-":
    print(first_val - second_val)
elif cal == "*":
    print(first_val * second_val)
elif cal == "/":
    print(first_val / second_val)

Below screenshot shows how we can create a calculator without function.

Calculator in python without function
Calculator in python without function

Calculator in Python code

In this, we will see the code for a calculator in Python. Here, we create an individual function to perform the operation like add, subtract, multiply, and divide. It will accept the user’s input along with the choice of operator and return the result.

Example:

def add(x, y):
   return x + y
def subtract(x, y):
   return x - y
def multiply(x, y):
   return x * y
def divide(x, y):
   return x / y
print("select an operation")
print("+")
print("-")
print("*")
print("/")
choice = input("Enter any operator to use")
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if choice == '+':
   print(a,"+",b,"=", add(a,b))
elif choice == '-':
   print(a,"-",b,"=", subtract(a,b))
elif choice == '*':
   print(a,"*",b,"=", multiply(a,b))
elif choice == '/':
   print(a,"/",b,"=", divide(a,b))
else:
   print("Invalid input")

You can see the below screenshot for calculator in python code and the output.

Calculator in python code
Calculator in python code

Output:

Calculator in python code
Calculator in python code

This is how we can make a calculator in Python.

Read: Python Tkinter Mainloop

Python Tkinter Calculator

Let us see how to create a simple calculator using Python Tkinter. I hope this Python Tkinter calculator example will help you to create a simple calculator in Python.

If you are new to Python GUI programming or Python Tkinter, check out Python GUI Programming (Python Tkinter)

Create a Simple Calculator using Python Tkinter

Planning for Python Tkinter Calculator

In this section, we will discuss the secret of training yourself before writing code for the python Tkinter calculator. We will discuss the look of an application, the functions it is going to perform, and the source of inspiration.

  • The source of inspiration is the calculator on the Windows 10 operating system.
  • It has a grey background in the display & black background on the buttons.
  • The text color of the entire application is white.
  • The application always opens at the bottom right side.
  • Numbers are displayed on the right side of the screen.

After observing the entire windows 10 calculator application, now it’s time to write things we are going to use or implement in our application.

  1. Every time application will open on the bottom right side.
  2. the application will have a grey background in the display & black background in the buttons.
  3. The text color of the entire application will be white
  4. a window will have a fixed size & can’t be resized.
  5. The calculator will have the basic functionality of addition, subtraction, multiplication & division.
  6. Numbers will be displayed on the right side of the screen.

Algorithm to Create Python Tkinter Calculator

In this section, we will discuss the algorithm for creating a python Tkinter calculator. Also, we will provide the data-flow diagram (DFD) for the same.

ws = Tk()
ws.title('Calculator')
ws.geometry('250x400+500+100')
ws.resizable(0,0)

  • the first line of the code is used to initialize the parent layer.
  • the second line is used to set the title of the window. The title is the name on the top of the window next to the feather.
  • the third line is set the width, height & position of the window.
    • width = 250
    • height = 400
    • position x = 500
    • position y = 100
  • Resizable determines the amount of screen that can be stretched. The screen can be stretched on the x & y-axis. Since we have provided both the values as 0. That means the screen can’t be stretched either way.
READ:  Pandas find duplicates in Python [5 Examples]

frame_1 = Frame(ws)
frame_1.pack(expand=True, fill=BOTH)

  • To place widgets like labels & buttons we have to create 4 frames.
  • Each frame is allowed to fully expand in the x and y direction if space is available.
  • In this way all the frames will have similar space & buttons placed in them will have symmetry.
    • expand=True : This allows for expansion in the available space.
    • fill=both : direction for espansion

key_1 = Button(
frame_1,
text='1',
font=('Arial', 22),
border = 0,
relief = GROOVE,
bg = '#2E2E2B',
fg = 'white',
command = lambda: display(1)
)

In this code, we are creating a button. To understand the button please refer to our button section. Here, under the command, we can call a function but we cannot pass an argument to a function. That is why we have used the anonymous function lambda here. To know more about the anonymous function please refer to our section on the anonymous function.

Here is the DFD of calculator

python tkinter calculator algorithm

Global Variables

num = ''
  • Variables used in a function are limited to that function only
  • if we want to use a particular variable in other function
  • then we have to declare that variable as a global variable.
  • In this code, we have declared num as a global variable.
  • any function referring to this variable must use the global keyword before the variable name
  • Changes made by any function on this variables will be observed by other functions too.
  • for example, if any function sets the value of the num to ’10’ then other functions using num will also have num value as ’10’.

Explaining function:

equal_btn()

def equal_btn():
     global num
     add=str(eval(num))
     scr_lbl['text'] = add
     num=''
  • equal_btn() function is used multiple times with the slight change in variable name in line 3 & line 4.
  • here, built-in function eval() plays an important role.
  • eval() takes a string as input and converts it into an integer & performs the operation.
  • that means if the string ‘2+3’ is passed to eval it will return 5 as output
python tkinter calculator using eval function

def clear_scr(number)

def clear_scr():
    global num
    num = ''
    scr_lbl['text'] = num
  • this function is called when C is clicked by user.
  • it clears everything on the display and sets the value of num to empty string.

def display(number)

def display(number):
    global num 
    num = num + str(number)
    scr_lbl['text'] = num
  • this function is responsible for displaying numbers on the screen.
  • every time user clicks on the numbered button, it concat with the existing string.
  • so when clicking on 1 it displays 1 on the screen. then when we click on 2 it displays 12 and so on.
READ:  Pandas Replace Multiple Values in Column based on Condition in Python [4 Methods]

Code:

from tkinter import *

ws = Tk()
ws.title('Calculator')
ws.geometry('250x400+500+100')
ws.resizable(0,0)

# global variables
num = ''

# functions
def display(number):
    global num 
    num = num + str(number)
    scr_lbl['text'] = num
    

def clear_scr():
    global num
    num = ''
    scr_lbl['text'] = num


def equal_btn():
     global num
     add=str(eval(num))
     scr_lbl['text'] = add
     num=''
def equal_btn():
     global num
     sub=str(eval(num))
     scr_lbl['text'] = sub
     num=''     
def equal_btn():
     global num
     mul=str(eval(num))
     scr_lbl['text'] = mul
     num=''
def equal_btn():
     global num
     div=str(eval(num))
     scr_lbl['text'] = div
     num=''    

var = StringVar()

# frames 
frame_1 = Frame(ws) 
frame_1.pack(expand=True, fill=BOTH)

frame_2 = Frame(ws)
frame_2.pack(expand=True, fill=BOTH)

frame_3 = Frame(ws)
frame_3.pack(expand=True, fill=BOTH)

frame_4 = Frame(ws)
frame_4.pack(expand=True, fill=BOTH)

# label
scr_lbl = Label(
    frame_1,
    textvariable='',
    font=('Arial', 20),
    anchor = SE,
    bg = '#595954',
    fg = 'white' 
    )

scr_lbl.pack(expand=True, fill=BOTH)

# buttons
key_1 = Button(
    frame_1,
    text='1',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(1)
    )

key_1.pack(expand=True, fill=BOTH, side=LEFT)

key_2 = Button(
    frame_1,
    text='2',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(2)
    )

key_2.pack(expand=True, fill=BOTH, side=LEFT)

key_3 = Button(
    frame_1,
    text='3',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(3)
    )

key_3.pack(expand=True, fill=BOTH, side=LEFT)

key_add = Button(
    frame_1,
    text='+',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display('+')
    )

key_add.pack(expand=True, fill=BOTH, side=LEFT)

key_4 = Button(
    frame_2,
    text='4',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(4)
    )

key_4.pack(expand=True, fill=BOTH, side=LEFT)

key_5 = Button(
    frame_2,
    text='5',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(5)
    )

key_5.pack(expand=True, fill=BOTH, side=LEFT)

key_6 = Button(
    frame_2,
    text='6',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(6)
    )

key_6.pack(expand=True, fill=BOTH, side=LEFT)

key_sub = Button(
    frame_2,
    text='-',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display('-')
    )

key_sub.pack(expand=True, fill=BOTH, side=LEFT)

key_7 = Button(
    frame_3,
    text='7',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(7)
    )

key_7.pack(expand=True, fill=BOTH, side=LEFT)

key_8 = Button(
    frame_3,
    text='8',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(8)
    )

key_8.pack(expand=True, fill=BOTH, side=LEFT)

key_9 = Button(
    frame_3,
    text='9',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(9)
    )

key_9.pack(expand=True, fill=BOTH, side=LEFT)

key_mul = Button(
    frame_3,
    text='*',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display('*')
    )

key_mul.pack(expand=True, fill=BOTH, side=LEFT)


key_clr = Button(
    frame_4,
    text='C',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = clear_scr 
    )

key_clr.pack(expand=True, fill=BOTH, side=LEFT)

key_0 = Button(
    frame_4,
    text='0',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display(0)
    )

key_0.pack(expand=True, fill=BOTH, side=LEFT)

key_res = Button(
    frame_4,
    text='=',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = equal_btn
    )

key_res.pack(expand=True, fill=BOTH, side=LEFT)

key_div = Button(
    frame_4,
    text='/',
    font=('Arial', 22),
    border = 0,
    relief = GROOVE,
    bg = '#2E2E2B',
    fg = 'white',
    command = lambda: display('/')
    )

key_div.pack(expand=True, fill=BOTH, side=LEFT)

ws.mainloop()

Output:

python tkinter calculator
Python tkinter calculator

So in this tutorial, we have learned about how to create a calculator using Python tkinter.

You may like the following Python tutorials:

This is how to make a calculator in Python using various methods.