Home » General Python Tutorials » How to Make a Simple Calculator using Python tkinter

How to Make a Simple Calculator using Python tkinter

Table of Contents

In today’s article, we are going to make a simple calculator App using the tkinter library in Python, let’s get started.

Necessary Libraries

For the code to function properly, make sure to install the tkinter library via the terminal or your command prompt:

$ pip install tk 

Imports

import tkinter as tk

We start by importing the tkinter library as tk which allows us to use all its functions by using tk.

Calculator App Class

class CalculatorApp:
   def __init__(self, root):
       self.root = root
       self.root.title("Simple Calculator - The Pycodes")
       self.root.geometry("350x430")
       self.root.resizable(False, False)
       self.root.configure(bg="#1e1e1e")

       self.equation = ""

       self.create_widgets()

Next, we create a class which is a blueprint for our Calculator, then give our window a title set its geometry and background color, and disable its resizing, after that, we create instance Variables:

  • One is self.root that is going to store the main window and the other.
  • Second, self.equation that is going to keep track of the mathematical expressions.

Creating Widgets

   def create_widgets(self):
       self.result_var = tk.StringVar()


       entry_frame = tk.Frame(self.root, bg="#1e1e1e")
       entry_frame.grid(row=0, column=0, columnspan=4, pady=20)


       entry = tk.Entry(entry_frame, font=("Arial", 24), textvariable=self.result_var, bd=0, insertwidth=4, width=14,
                        justify="right", bg="#1e1e1e", fg="white")
       entry.grid(row=0, column=0, ipady=8)


       buttons = [
           ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
           ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
           ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
           ('C', 4, 0), ('0', 4, 1), ('=', 4, 2), ('+', 4, 3)
       ]

       for (text, row, column) in buttons:
           btn = tk.Button(self.root, text=text, font=("Arial", 18), width=5, height=2, bd=1, fg="#fff", bg="#2a2d36",
                           command=lambda t=text: self.button_click(t))
           btn.grid(row=row, column=column, padx=5, pady=5)

       self.root.bind('<Return>', lambda event: self.button_click('='))

Following that, we create and manage the visual parts that the user is gonna use.

  • So as a start, we begin by using StringVar which is a tkinter variable to update the displayed result dynamically.
  • Secondly, we create a frame where we are going to place the buttons then we make an entry widget where the result is going to be displayed.
  • Thirdly we bound the entry widget to the StringVar so that any changes in the self.result_var will show in the entry widget.
  • Fourth we create the buttons that hold the numbers and the mathematical signs and place them in a grid layout while giving them a specific styling and linking each of them to the button_click function which is triggered when the button is pressed.

Button Click Function

   def button_click(self, value):
       if value == 'C':
           self.equation = ""
       elif value == '=':
           try:
               result = str(eval(self.equation))
               self.equation = result
           except Exception as e:
               result = "Error"
       else:
           self.equation += value

       self.result_var.set(self.equation)

For this step, we define a function that gets called when any button is pressed performing a specific action based on the clicked button for example C clears the current equation, = evaluates the current equation, and if the evaluation is successful it displays the result. Otherwise, an error message is displayed in the entry widget, and so on for the other buttons.

Main Block

if __name__ == "__main__":
   root = tk.Tk()
   app = CalculatorApp(root)
   root.mainloop()

Lastly, this part initializes the main window and keeps it running in a loop so that the user can use the different elements of the graphical user interface until he chooses to exit the main window.

Example

This is the final result you get once you run the code:

Full Code

import tkinter as tk


class CalculatorApp:
   def __init__(self, root):
       self.root = root
       self.root.title("Simple Calculator - The Pycodes")
       self.root.geometry("350x430")
       self.root.resizable(False, False)
       self.root.configure(bg="#1e1e1e")


       self.equation = ""


       self.create_widgets()


   def create_widgets(self):
       self.result_var = tk.StringVar()


       entry_frame = tk.Frame(self.root, bg="#1e1e1e")
       entry_frame.grid(row=0, column=0, columnspan=4, pady=20)


       entry = tk.Entry(entry_frame, font=("Arial", 24), textvariable=self.result_var, bd=0, insertwidth=4, width=14,
                        justify="right", bg="#1e1e1e", fg="white")
       entry.grid(row=0, column=0, ipady=8)


       buttons = [
           ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
           ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
           ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
           ('C', 4, 0), ('0', 4, 1), ('=', 4, 2), ('+', 4, 3)
       ]


       for (text, row, column) in buttons:
           btn = tk.Button(self.root, text=text, font=("Arial", 18), width=5, height=2, bd=1, fg="#fff", bg="#2a2d36",
                           command=lambda t=text: self.button_click(t))
           btn.grid(row=row, column=column, padx=5, pady=5)


       self.root.bind('<Return>', lambda event: self.button_click('='))


   def button_click(self, value):
       if value == 'C':
           self.equation = ""
       elif value == '=':
           try:
               result = str(eval(self.equation))
               self.equation = result
           except Exception as e:
               result = "Error"
       else:
           self.equation += value


       self.result_var.set(self.equation)


if __name__ == "__main__":
   root = tk.Tk()
   app = CalculatorApp(root)
   root.mainloop()

Happy Coding!

Learn also: How to Make a Simple Interest Calculator using Python

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top