Create a Functional GUI Calculator Using Python's Tkinter: A Step-by-Step Guide

By ✦ min read

Introduction

Building a graphical user interface (GUI) calculator is an excellent beginner project for anyone learning Python. It introduces you to event-driven programming and widget management using Tkinter, Python's built-in GUI toolkit. In this guide, you will create a simple arithmetic calculator featuring digit buttons (0–9), basic operators (+, -, *, /), an equals button, and an All Clear (AC) button. The calculator will have a fixed-size window with an output screen at the top. By the end, you'll have a working application you can run and even expand.

Create a Functional GUI Calculator Using Python's Tkinter: A Step-by-Step Guide
Source: www.freecodecamp.org

What You Need

Step-by-Step Instructions

Step 1: Import Tkinter and Create the Main Window

Open your editor and create a new Python file (e.g., calculator.py). Start by importing the Tkinter module:

import tkinter as tk

Then initialize the main application window using the Tk() class:

root = tk.Tk()

This window serves as the container for all other widgets. To keep it visible, you must call root.mainloop() at the end of your script. However, we will add widgets first.

Step 2: Name and Configure the Window

Give the window a title and make it non‑resizable:

root.title("Simple Calculator")
root.resizable(False, False)

The resizable(False, False) call prevents users from stretching the window, keeping the layout intact.

Step 3: Create Frames for Layout

Frames help organize widgets. We will use two frames: one for the output (display) area and one for the button grid.

display_frame = tk.Frame(root)
button_frame = tk.Frame(root)

Pack the frames vertically:

display_frame.pack(pady=10)
button_frame.pack()

Step 4: Add the Output Screen

Use an Entry widget to show the user’s input and results. Set its state to 'readonly' to prevent direct typing, and give it a suitable width.

output = tk.Entry(display_frame, width=30, font=('Arial', 14), justify='right', state='readonly')
output.grid(row=0, column=0, padx=5, pady=5)

Note: We'll change the state to normal temporarily when updating the text.

Step 5: Add Number and Operator Buttons

Create a list of button labels and place them in the button frame using a grid layout. For example:

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+'
]

Loop through the list and create buttons, attaching a common command lambda that captures the label. For digits and operators (except '='), we will write a function button_click that appends the label to the output. For '=', we'll call calculate.

Example button creation inside the loop:

btn = tk.Button(button_frame, text=label, width=5, height=2,
                command=lambda l=label: button_click(l) if l != '=' else calculate())
btn.grid(row=row, column=col, padx=2, pady=2)

Step 6: Implement the Button Click Function

Define button_click(value) that inserts the value into the output box:

Create a Functional GUI Calculator Using Python's Tkinter: A Step-by-Step Guide
Source: www.freecodecamp.org
def button_click(value):
    current = output.get()
    output.config(state='normal')
    output.delete(0, tk.END)
    output.insert(0, current + value)
    output.config(state='readonly')

Step 7: Implement the Calculation

The calculate function evaluates the expression in the display. Use Python’s built‑in eval() cautiously (for a simple local calculator it’s acceptable). Handle errors gracefully.

def calculate():
    try:
        result = eval(output.get())
        output.config(state='normal')
        output.delete(0, tk.END)
        output.insert(0, str(result))
        output.config(state='readonly')
    except:
        output.config(state='normal')
        output.delete(0, tk.END)
        output.insert(0, "Error")
        output.config(state='readonly')

Step 8: Add the AC (All Clear) Button

Create a separate button that clears the display. Place it below the digit grid (or within the grid using columnspan).

clear_btn = tk.Button(button_frame, text='AC', width=11, height=2,
                      command=lambda: clear_display())
clear_btn.grid(row=4, column=0, columnspan=2, padx=2, pady=2)

Define the clear_display function:

def clear_display():
    output.config(state='normal')
    output.delete(0, tk.END)
    output.config(state='readonly')

Step 9: Run the Application

Finally, start the main event loop:

root.mainloop()

Save the file and run it with Python. Your calculator should appear and be functional!

Tips for Success

Tags:

Recommended

Discover More

Emergency Patch Alert: Critical Zero-Day in cPanel Actively Exploited Amid Major BreachesHigh-Fidelity Racing Simulations Arrive on Apple Vision Pro with iRacing ConnectHow to Track App Download Trends and Respond to SlowdownsBuilding Complex Simulations with HASH: A Practical Step-by-Step GuideIsolating AI Agents: A Practical Guide to Sandboxing Strategies