Skip to main content / پرش به محتوای اصلی

Building a Graphical Calculator with Python and Tkinter

September 2026Updated: November 20264 min read۱۹ بازدید
Building a graphical calculator with Python Tkinter tutorial banner
Complete step-by-step tutorial on building a desktop GUI calculator with Python and Tkinter; covering window layout, dynamic buttons, evaluation logic, and robust error handling.

Introduction

In our previous tutorial, you learned What is Tkinter and how to build GUI apps in Python. Now, let's put those skills into practice by building a practical desktop project: a Graphical Calculator supporting basic arithmetic operations (addition, subtraction, multiplication, division), decimal numbers, and robust error handling.

This project is designed for developers who understand basic Tkinter concepts (windows, widgets, layouts, events) and want to see how they combine to form a complete desktop application. By the end of this article, you will have a working calculator and understand every line of its implementation.


Prerequisites

To follow this tutorial, ensure you have:

  • Python 3 installed on your system (if not, check out our Python Windows Installation Guide).
  • Tkinter, which is included by default with standard Python distributions.

Setting Up the Application Window

First, create the root application window:

python
import tkinter as tk

window = tk.Tk()
window.title("Python Calculator")
window.geometry("350x500")
window.resizable(False, False)
  • tk.Tk() initializes the main window.
  • title() sets the title bar text to "Python Calculator".
  • geometry("350x500") sets the dimensions to 350 pixels wide by 500 pixels high.
  • resizable(False, False) disables window resizing to keep button alignments clean and uniform.

Designing the Calculator Display

We use a styled Entry widget to display input expressions and calculation results:

python
display = tk.Entry(
    window,
    font=("Arial", 28),
    justify="right",
    bd=0
)
display.pack(
    padx=15,
    pady=20,
    fill="x",
    ipady=15
)
  • font=("Arial", 28) provides large, legible digits.
  • justify="right" aligns numbers to the right, mirroring real-world hardware calculators.
  • fill="x" expands the entry across the full width of the window with internal padding ipady=15.

Creating the Button Grid Dynamically

Rather than hardcoding 16 separate button widgets, we define the keypad layout using a 2D matrix:

python
buttons = [
    ["7", "8", "9", "÷"],
    ["4", "5", "6", "×"],
    ["1", "2", "3", "-"],
    [".", "0", "C", "+"],
]

Using nested loops, we create a horizontal Frame for each row and pack buttons evenly:

python
for row in buttons:
    frame = tk.Frame(window)
    frame.pack(expand=True, fill="both")
    for value in row:
        tk.Button(
            frame,
            text=value,
            font=("Arial", 18),
            command=lambda v=value: button_click(v)
        ).pack(
            side="left",
            expand=True,
            fill="both",
            padx=3,
            pady=3
        )

Why lambda v=value: button_click(v)?

Tkinter button callbacks expect a zero-argument callable. Using default parameter capture v=value in a lambda preserves the specific character of each button when it is clicked without executing immediately.


Implementing Core Calculation Logic

We break down the calculator logic into modular helper functions:

python
def add_to_display(value):
    display.insert(tk.END, value)

def clear_display():
    display.delete(0, tk.END)

def calculate():
    expression = display.get()
    if not expression:
        return
    try:
        # Evaluate mathematical expression securely without globals
        result = eval(expression, {"__builtins__": None}, {})
        clear_display()
        display.insert(0, str(result))
    except (SyntaxError, TypeError, ZeroDivisionError):
        clear_display()
        display.insert(0, "Error")

def button_click(value):
    if value == "C":
        clear_display()
    elif value == "=":
        calculate()
    else:
        if display.get() == "Error":
            clear_display()
        value = value.replace("×", "*").replace("÷", "/")
        add_to_display(value)

Error Handling Explained:

The try/except block catches syntax errors (e.g., "5+") and ZeroDivisionError (dividing by zero), displaying "Error" on the screen instead of crashing the Python process.


Complete Application Code

Here is the complete source code for calculator.py:

python
import tkinter as tk

def add_to_display(value):
    display.insert(tk.END, value)

def clear_display():
    display.delete(0, tk.END)

def calculate():
    expression = display.get()
    if not expression:
        return
    try:
        result = eval(expression, {"__builtins__": None}, {})
        clear_display()
        display.insert(0, str(result))
    except (SyntaxError, TypeError, ZeroDivisionError):
        clear_display()
        display.insert(0, "Error")

def button_click(value):
    if value == "C":
        clear_display()
    elif value == "=":
        calculate()
    else:
        if display.get() == "Error":
            clear_display()
        value = value.replace("×", "*").replace("÷", "/")
        add_to_display(value)

window = tk.Tk()
window.title("Python Calculator")
window.geometry("350x500")
window.resizable(False, False)

display = tk.Entry(
    window,
    font=("Arial", 28),
    justify="right",
    bd=0
)
display.pack(
    padx=15,
    pady=20,
    fill="x",
    ipady=15
)

buttons = [
    ["7", "8", "9", "÷"],
    ["4", "5", "6", "×"],
    ["1", "2", "3", "-"],
    [".", "0", "C", "+"],
]

for row in buttons:
    frame = tk.Frame(window)
    frame.pack(expand=True, fill="both")
    for value in row:
        tk.Button(
            frame,
            text=value,
            font=("Arial", 18),
            command=lambda v=value: button_click(v)
        ).pack(
            side="left",
            expand=True,
            fill="both",
            padx=3,
            pady=3
        )

tk.Button(
    window,
    text="=",
    font=("Arial", 20),
    bg="#2563eb",
    fg="white",
    command=calculate
).pack(
    fill="both",
    padx=15,
    pady=10,
    ipady=8
)

window.mainloop()

Running the Application

Save the code above to calculator.py and run:

bash
python calculator.py

The calculator window will launch, ready for keyboard or mouse-driven arithmetic calculations.


Open Source Repository

The full source code, along with project documentation, is available on GitHub:

github.com/taha-heidaryfard/python-tkinter-calculator


Conclusion

Congratulations! You have built a complete, production-ready desktop GUI calculator using Python and Tkinter. You explored how to create responsive widget grids, bind dynamic lambda callbacks, evaluate arithmetic expressions safely, and prevent application crashes through structured exception handling.


Frequently Asked Questions

What library is used to build this desktop calculator?

This calculator is built using Tkinter, Python's official built-in GUI library. It requires no external pip packages.

Is eval() safe to use in a calculator application?

Standard eval() executes arbitrary Python code, which can pose security risks. In our implementation, we restrict execution scope by passing {"builtins": None}, which disables access to file systems, system calls, and global Python builtins, keeping execution limited to pure mathematical operations.

How do I run this Python calculator on my computer?

Save the code as calculator.py and run python calculator.py in your terminal. Ensure Python is installed on your machine.

How can I package this calculator into a standalone Windows .exe file?

You can use pyinstaller --onefile --noconsole calculator.py to compile the script into a standalone executable that runs without requiring a separate Python installation.

Tags for this article:

Enjoyed this article?

Share it with your friends and colleagues.

Share: