Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 40 ยท Projects and Practice

Project: Build a Calculator with Tkinter

Build a calculator in Tkinter: a tested calculation engine, a safe expression parser without eval, a grid of buttons, keyboard input, history and error handling.

A calculator is the classic first GUI project because it touches everything: a grid of buttons, a display, event handling and, most importantly, logic that must be correct. It is also the project where the usual beginner solution, calling eval() on the display text, is both tempting and dangerous.

In this project you build the calculator in three layers: a calculation engine (plain Python, fully tested here), a safe expression evaluator that does not use eval, and a Tkinter window that wires them together. The engine and the evaluator run in the in-browser runner. The window code is read-only because Tkinter needs a screen; it is short on purpose, because the logic is already proven.

Step 1: What the calculator should do

  • Digits 0-9 and a decimal point.
  • Operators + - ร— รท, equals, clear (C), backspace, sign toggle and percent.
  • Keyboard input: digits, + - * /, Enter, Backspace, Escape.
  • Errors shown as text ("Cannot divide by zero") instead of crashing.
  • A history of the last results.

We will use the simple "pocket calculator" model: you type a number, press an operator, type another number, press equals. Chained operations (2 + 3 ร— 4) evaluate left to right, as on a basic handheld calculator. After that we also build an expression-mode evaluator that respects the usual precedence.

Step 2: The engine as a state machine

The engine keeps four values: the text being typed, the stored left operand, the pending operator, and whether the next digit should start a new number. A button press is a method call; the display is a property. No widget is involved.

Python
class Calculator:
    def __init__(self):
        self.clear()

    def clear(self):
        self.entry = "0"
        self.left = None
        self.op = None
        self.fresh = True        # next digit replaces the display
        self.error = None

The complete engine and tests follow. Read the tests first: they are the specification.

Python Run: the calculator engine with tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the choices: Decimal instead of float so that 0.1 + 0.2 shows 0.3; a limit on digits so the display does not overflow; division by zero becomes an error state that the next digit clears. Every behavior has a test line, and you can add more before touching the GUI.

Step 3: A safe expression evaluator

Many calculators offer an "expression" mode: the user types 2 + 3 * (4 - 1) and presses Enter. The lazy way is eval(text), which executes any Python, including __import__('os').system(...). Never use eval on user input, even in a desktop program (people paste text from the internet).

The safe way is to parse the text with Python's ast module and walk the tree, allowing only numbers and arithmetic operators:

Python Run: a safe evaluator without eval

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The attack string and the huge exponent are rejected with "Invalid expression" while ordinary arithmetic keeps its normal precedence. This function is also a good candidate for the model layer: it has no Tkinter inside.

Step 4: The window

The window has one Label for the display and a grid of buttons. The layout is data: a list of rows.

Python
import tkinter as tk
from tkinter import ttk

LAYOUT = [
    ["C", "~", "%", "/"],
    ["7", "8", "9", "*"],
    ["4", "5", "6", "-"],
    ["1", "2", "3", "+"],
    ["0", ".", "<", "="],
]
LABELS = {"/": "รท", "*": "ร—", "~": "ยฑ", "<": "โŒซ", "-": "โˆ’"}

class CalculatorApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Calculator")
        self.resizable(False, False)
        self.calc = Calculator()

        self.display = tk.StringVar(value="0")
        ttk.Label(self, textvariable=self.display, anchor="e",
                  font=("Segoe UI", 28), padding=(12, 16)).grid(row=0, column=0, sticky="ew")

        pad = ttk.Frame(self, padding=6)
        pad.grid(row=1, column=0)
        for r, row in enumerate(LAYOUT):
            for c, key in enumerate(row):
                ttk.Button(pad, text=LABELS.get(key, key), width=5,
                           command=lambda k=key: self.press(k)).grid(row=r, column=c, padx=2, pady=2, ipady=8)

        self.bind("<Key>", self.on_key)
        self.bind("<Return>", lambda e: self.press("="))
        self.bind("<BackSpace>", lambda e: self.press("<"))
        self.bind("<Escape>", lambda e: self.press("C"))

    def press(self, key):
        press(self.calc, key)
        self.display.set(self.calc.display)

    def on_key(self, event):
        if event.char and event.char in "0123456789.+-*/%":
            self.press(event.char)

You see a window with a right-aligned large display on top and four columns of buttons below it. Clicking 1, 2, +, 3, = shows 15. The same sequence typed on the keyboard works. Things to notice:

  • lambda k=key: self.press(k) captures each button's key (without k=key all buttons would press the last one).
  • The button layout is data, so adding a row (square root, memory keys) is one list entry.
  • press is the same function used in the tests, so GUI and tests cannot disagree.
  • self.bind("<Key>") receives every key; event.char filters the ones we accept. See the Events and Bindings chapter for details.

Step 5: History

Record completed calculations in a list and show them in a Listbox or Treeview. The engine can keep it itself, and the test is trivial:

Python Run: a history list that stays bounded

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the window you would call history.add(...) after each = and refresh the list with listbox.delete(0, "end") followed by insert.

Extensions to try

  • Add a memory (M+, Mโˆ’, MR, MC).
  • Add โˆš, xยฒ and 1/x keys.
  • Add a scientific mode with a Notebook, or a second layout toggled by a menu item.
  • Copy the result with self.clipboard_clear() and self.clipboard_append(text).
  • Switch to the expression evaluator and show a live preview of the result while typing.
  • Add a theme switch using ttk styles (Styles and Themes).

Common mistakes

  • Using eval on the display text.
  • Using float for money-like arithmetic and showing 0.30000000000000004.
  • Forgetting the late-binding k=key trick in the button loop.
  • Mixing display formatting with calculation: store numbers as numbers or Decimal, format only when showing.
  • Letting the display grow wider than the window (limit digits).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is eval(display_text) a bad idea for a calculator?

    Parse with ast and allow only numbers and arithmetic operators instead.
  2. 2. Why use Decimal for the engine?

    Decimal does exact decimal arithmetic, which matches what users expect.
  3. 3. What does lambda k=key: self.press(k) fix in the button loop?

    A default argument is evaluated when the lambda is created, so each button gets its own copy.
  4. 4. What is the main benefit of keeping the engine free of Tkinter?

    Pure logic is easy to test, as the test table above shows.

Summary

  • Build the calculator in layers: engine, evaluator, window.
  • Use Decimal, limit digits and treat division by zero as a state, not a crash.
  • Parse expressions with ast; never eval user text.
  • Describe the keypad as data and share one press function between the GUI and the tests.
  • Extend with history, memory and themes.

Next: Project: A To-Do List App