Make a Calculator In Python using Tkinter

In this Python tutorial, I will explain to you how to make a calculator in Python that can add, subtract, divide, and multiply depending on the user-entered input. You’ll learn how to build a simple and interactive command-line interface, validate user input for basic error handling, etc.

Let’s get in!

Calculator in Python Tkinter

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

As you can see, we have created a simple calculator in Python, which can perform different arithmetical operations like add, subtract, multiply, and divide. The user-defined functions are 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

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’s entered choice, it will operate.

calculator in Python

Check out Read a Text File and Display the Contents in a Tkinter Window With Python

Calculator in Python using a 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, 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 the code with the output.

Calculator in python using class

Output:

Calculator in python using class

Check out Create Message Boxes with Python Tkinter

Calculator in Python without a function

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

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)

The screenshot below shows how we can create a calculator without a 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 screenshot below for the calculator in Python code and the output.

Calculator in python code

Output:

Calculator in python code

Check out Create a Search Box with Autocomplete in Python Tkinter

Algorithm to Create a 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 sets 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.
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 directions 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 expansion
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 the 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 another 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 these 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 the num value of ’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 the user.
  • It clears everything on the display and sets the value of num to an 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 the user clicks on the numbered button, it concatenates 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.

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

So in this tutorial, I have explained how to create a calculator using Python tkinter.

You may like the following Python tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.