Create a Basic Calculator in Python Using Tkinter

Basic Calculator in Python with Tkinter

Introduction

In this tutorial, we will create a Basic Calculator in Python using the Tkinter library. It will allow you to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

Calculators are everyday tools that many of us take for granted, but understanding how to build one from scratch can be a joyful experience. By the end of this tutorial, youā€™ll not only have a functional calculator but also a deeper understanding of the capabilities of Python and Tkinter.

So, whether youā€™re a Python newbie looking to brush up on your programming skills or an experienced developer looking for a fun project, letā€™s dive into the world of GUI development and create a calculator you can proudly call your own.

Requirements

Before we begin, make sure you have Python installed on your system. You will also need Tkinter, which comes pre-installed with most Python distributions. If you donā€™t have Tkinter, you can install it using pip:

pip install tk

Start Writing the Code

Create a separate directory for this project, naming it ā€œCalculator_Appā€. Within this directory, generate a fresh Python file named ā€œcalculator.pyā€, and open it with your favorite text editor. Now start writing the code.

Import Tkinter

First, import the Tkinter library and create the main application window.

import tkinter as tk

# Create the main application window
root = tk.Tk()
root.title("Calculator")

Design the Calculator Interface

Now, letā€™s design the calculator interface by adding buttons and a display area for the input and output.

# Create an Entry widget for the display
display = tk.Entry(root, width=20, font=("Arial", 20))
display.grid(row=0, column=0, columnspan=4, ipadx= 46, ipady= 40)

# Define button labels
button_labels = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+'
]

# Create buttons and place them in a grid
row, col = 1, 0
buttons = []
for label in button_labels:
    button = tk.Button(root, text=label, width=5, height=2, font=("Arial", 16))
    button.grid(row=row, column=col, padx=5, pady=5)
    buttons.append(button)
    col += 1
    if col > 3:
        col = 0
        row += 1

In the above code, weā€™ve created an Entry widget for the display and a grid of buttons labeled with numbers, arithmetic operators, and the equals sign.

Create the Calculator Functions

Next, letā€™s define the functions that handle the calculatorā€™s operations when buttons are clicked.

def button_click(event):
    # Get the current text in the display
    current = display.get()
    
    # Get the label of the button that was clicked
    button = event.widget
    text = button['text']
    
    if text == '=':
        try:
            # Evaluate the expression and display the result
            result = eval(current)
            display.delete(0, tk.END)
            display.insert(tk.END, str(result))
        except:
            # Handle errors (e.g., division by zero)
            display.delete(0, tk.END)
            display.insert(tk.END, "Error")
    else:
        # Append the button's text to the current display text
        display.insert(tk.END, text)

def clear():
    # Clear the display
    display.delete(0, tk.END)

In the ā€˜button_clickā€˜ function, we handle button clicks. When the ā€˜=ā€˜ button is clicked, we evaluate the expression in the entry widget and display the result. If an error occurs (e.g., division by zero), we display ā€œError.ā€ For other buttons, we simply append their text to the current display text.

The ā€˜clearā€˜ function is used to clear the display when the ā€˜Cā€™ button is clicked.

Binding Functions to Buttons

Finally, we need to bind the ā€˜button_clickā€˜ function to the calculator buttons and the ā€˜clearā€˜ function to the ā€˜Cā€™ button.

# Bind the button_click function to the calculator buttons
for button in buttons:
    button.bind("<Button-1>", button_click)

# Create a clear button and bind the clear function
clear_button = tk.Button(root, text="C", width=5, height=2, font=("Arial", 16), command=clear)
clear_button.grid(row=5, column=0, columnspan=4, padx=5, pady=5)

Running the Calculator

Now that weā€™ve defined our calculator interface and functions, we can run the calculator by starting the Tkinter main loop.

root.mainloop()

Output

python calculator app

Summary

In this tutorial, weā€™ve created a basic calculator using Python programming language. We used the Tkinter library to build the graphical interface of this app. This tutorial guides you through each step of the process, from designing the user interface to binding functions to buttons.

Whether youā€™re a beginner looking to enhance your programming proficiency or an experienced developer seeking a satisfying project, building a calculator app in Python with Tkinter is an excellent way to gain hands-on experience in GUI development.

So, roll up your sleeves, open your code editor, and embark on this exciting journey to create a user-friendly calculator application.

For more interesting Tkinter examples, please explore the dedicated page exclusively for Python Projects.

Happy Calculating!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iā€™m Subhankar Rakshit, the brains behind PySeek. Iā€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Ā 194