Creating a GUI Calculator in Python Using Tkinter: A Step-by-Step Guide

Introduction

Building a graphical user interface (GUI) calculator is an excellent project for Python beginners. In this guide, you'll learn how to create a functional arithmetic calculator using Tkinter, Python's built-in GUI library. This hands-on tutorial assumes you have basic Python knowledge and are ready to dive into visual programming. By the end, you'll have a working calculator with numeric buttons, operators, a display screen, and an "All Clear" function.

Creating a GUI Calculator in Python Using Tkinter: A Step-by-Step Guide
Source: www.freecodecamp.org

Prerequisites

Before starting, ensure you meet the following:

To verify Tkinter is installed, run this command in your terminal:

python -m tkinter

If a small window appears, Tkinter is ready. If not, you may need to reinstall Python or install Tkinter separately.

Project Overview

What We Are Building

Our calculator will have these features:

Below is a sketch of the user interface (UI) we will create:

(UI sketch placeholder – imagine a calculator layout)

Setting Up the Main Window

First, import Tkinter and create the main window instance:

import tkinter as tk
root = tk.Tk()

Then run the main loop to keep the window open:

root.mainloop()

Now you have a blank window.

Naming the Window

Set a title for your window with the title() method:

root.title("Simple Calculator")

Configuring the Window

To make the window non‑resizable, use:

root.resizable(False, False)

You can also set a fixed size, e.g., root.geometry("300x400").

Organizing with Frames

Frames help group widgets. We’ll use two frames:

top_frame = tk.Frame(root)
top_frame.pack(side=tk.TOP)

bottom_frame = tk.Frame(root)
bottom_frame.pack(side=tk.BOTTOM)

Building the Output Screen

Use a Text widget or an Entry widget to show numbers. We’ll use an Entry widget with right‑alignment for simplicity:

display = tk.Entry(top_frame, width=20, font=('Arial', 14), justify='right')
display.pack(pady=10)

Adding a Scrollbar (Optional)

If you want a scrollbar for long expressions, place it alongside the Entry (though calculators typically don’t scroll). For this tutorial, we skip it.

Creating the Button Grid

We’ll generate buttons in rows. Each button will call a function when clicked. Define a button creation helper:

def create_button(frame, text, row, col, command, width=5):
    btn = tk.Button(frame, text=text, width=width, command=command)
    btn.grid(row=row, column=col, padx=2, pady=2)
    return btn

Now, populate the bottom frame with digits and operators. For example, the first row of numbers (7,8,9):

Creating a GUI Calculator in Python Using Tkinter: A Step-by-Step Guide
Source: www.freecodecamp.org
create_button(bottom_frame, '7', 0, 0, lambda: press('7'))
create_button(bottom_frame, '8', 0, 1, lambda: press('8'))
create_button(bottom_frame, '9', 0, 2, lambda: press('9'))
create_button(bottom_frame, '/', 0, 3, lambda: press('/'))

Continue for all buttons (4,5,6,*, 1,2,3,-, 0,.,=, +).

Making Numbers Visible on the Screen

Define a press() function that appends the clicked button's text to the display:

def press(char):
    current = display.get()
    display.delete(0, tk.END)
    display.insert(0, current + char)

For the = button, we need to evaluate the expression. Use eval() carefully (in a real app, sanitize input):

def calculate():
    try:
        result = eval(display.get())
        display.delete(0, tk.END)
        display.insert(0, str(result))
    except Exception as e:
        display.delete(0, tk.END)
        display.insert(0, "Error")

Adding the AC (All Clear) Button

The AC button clears the display:

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

create_button(bottom_frame, 'AC', 4, 0, clear, width=10)

Place it in the last row, spanning two columns if desired.

Wrapping Up and Running the Application

Assemble all pieces in your script. Ensure you have the correct grid coordinates and that the root.mainloop() is called at the end. Run the script, and you should see a fully functional calculator.

Here is the complete code structure (run in order):

import tkinter as tk

def press(char): ...
def calculate(): ...
def clear(): ...

root = tk.Tk()
root.title("Simple Calculator")
root.resizable(False, False)

top_frame = tk.Frame(root)
top_frame.pack(side=tk.TOP)
display = tk.Entry(top_frame, ...)
display.pack()

bottom_frame = tk.Frame(root)
bottom_frame.pack(side=tk.BOTTOM)
# ... create all buttons ...

root.mainloop()

Next Steps and Customization

You can enhance your calculator:

For more Tkinter projects, check our introduction or continue with advanced GUI tutorials.

Happy coding!

Tags:

Recommended

Discover More

Android 17 Unveiled: Google's 'Gemini Intelligence' Ushers in a New Era of Proactive AIPredicting Volcanic Eruptions: Toward Reliable ForecastingUbuntu 16.04 LTS: End of Security Support – What You Need to KnowGlobal Math Gender Gap Widens Again: Girls Lose Ground in Latest International StudyFrom Experiment to Enterprise: A Practical Guide to Deploying AI Agents in Production