Create a Simple Calculator with Python and Tkinter: A Beginner’s Guide

Home » Blog » instrumentation » Create a Simple Calculator with Python and Tkinter: A Beginner’s Guide

Here’s an example program in Python using the Tkinter library to create a simple calculator

import tkinter as tk

class CalculatorApp:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        # Create display widget
        self.display = tk.Entry(master, width=20, font=('Arial', 14))
        self.display.grid(row=0, column=0, columnspan=4, pady=10)

        # Create number buttons
        self.create_button(1, 1, '1')
        self.create_button(1, 2, '2')
        self.create_button(1, 3, '3')
        self.create_button(2, 1, '4')
        self.create_button(2, 2, '5')
        self.create_button(2, 3, '6')
        self.create_button(3, 1, '7')
        self.create_button(3, 2, '8')
        self.create_button(3, 3, '9')
        self.create_button(4, 2, '0')

        # Create operation buttons
        self.create_button(1, 4, '+')
        self.create_button(2, 4, '-')
        self.create_button(3, 4, '*')
        self.create_button(4, 4, '/')
        self.create_button(4, 3, '.')
        self.create_button(4, 1, 'C')

        # Create equals button
        self.create_button(4, 0, '=', bg='green')

        # Initialize state
        self.reset()

    def create_button(self, row, col, text, bg='white'):
        button = tk.Button(self.master, text=text, width=5, height=2, bg=bg, font=('Arial', 14),
                           command=lambda: self.handle_button(text))
        button.grid(row=row, column=col, padx=5, pady=5)

    def handle_button(self, text):
        if text.isdigit() or text == '.':
            self.display.insert(tk.END, text)
        elif text in ['+', '-', '*', '/']:
            if self.operator:
                self.compute()
            else:
                self.result = float(self.display.get())
            self.operator = text
            self.display.delete(0, tk.END)
        elif text == '=':
            self.compute()
            self.operator = None
        elif text == 'C':
            self.reset()

    def compute(self):
        value = float(self.display.get())
        if self.operator == '+':
            self.result += value
        elif self.operator == '-':
            self.result -= value
        elif self.operator == '*':
            self.result *= value
        elif self.operator == '/':
            self.result /= value
        self.display.delete(0, tk.END)
        self.display.insert(0, str(self.result))

    def reset(self):
        self.display.delete(0, tk.END)
        self.operator = None
        self.result = 0.0


root = tk.Tk()
app = CalculatorApp(root)
root.mainloop()

This program creates a simple calculator with buttons for digits, decimal point, clear, addition, subtraction, multiplication, division, and equals. It uses the Entry widget for the display, and the Button widget for the buttons. The handle_button method is called when a button is clicked, and it updates the display and performs the appropriate calculation when necessary. The compute method is used to perform the actual calculations, and the reset method is used to reset the calculator state.

Leave a Comment

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