Building a Graphical Calculator with Python and Tkinter

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 application: 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:
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:
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 paddingipady=15.
Creating the Button Grid Dynamically
Rather than hardcoding 16 separate button widgets, we define the keypad layout using a 2D matrix:
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:
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:
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:
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:
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.
Tags for this article:
Related Articles

What is Tkinter? Python GUI Development Guide for Beginners
Comprehensive Tkinter tutorial for building desktop graphical user interfaces (GUIs) in Python; from core widgets and geometry managers to building a temperature converter app.

How to Install Python on Windows (2026 Complete Guide)
Step-by-step guide to installing Python on Windows in 2026 using both the CLI (winget) and the official installer, configuring PATH, and running your first program.

What is Python? Uses, Advantages, and Learning Path
Python is a high-level, open-source, general-purpose programming language. Learn why it has become the world's most popular language, what it is used for, and how to get started.