Creating a Functional GUI Calculator with Python's Tkinter

By

Building your first graphical user interface (GUI) in Python is an exciting milestone. One of the most approachable projects is a simple arithmetic calculator. In this guide, you'll learn step by step how to build a functioning calculator using Tkinter, Python's built-in library for creating desktop applications. By the end, you'll have a solid foundation for creating more complex GUI projects.

Prerequisites

Before diving in, make sure you have a basic understanding of Python syntax, how to import and use libraries, and how to work with module attributes. If you're comfortable with these concepts, you're ready to proceed.

Creating a Functional GUI Calculator with Python's Tkinter
Source: www.freecodecamp.org

What We're Building

We'll create a non-resizable calculator window with a numeric keypad (0–9), arithmetic operators (+, -, *, /, =), an output screen that displays input and results, and an AC (All Clear) button to reset the display. The layout will be clean and intuitive, mimicking a typical handheld calculator.

Setting Up the Main Window

First, confirm that Tkinter is installed by running python -m tkinter in your terminal. If a test window appears, you're good. Then, import Tkinter and initialize the main window:

import tkinter as tk
root = tk.Tk()
root.title("Calculator")
root.resizable(False, False)  # non-resizable

This window will serve as the container for all our widgets. Keep it open with root.mainloop() at the end.

Designing the Interface

Organizing with Frames

Use frames to divide the window into two sections: the top display area and the bottom button grid. Create a frame for the display and another for the buttons:

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

The Output Screen

Add an Entry widget for the display. Set it to read-only so users can only see input and results. You can also add a scrollbar if the text is long:

display = tk.Entry(display_frame, width=30, justify='right', state='readonly')
display.pack()
scrollbar = tk.Scrollbar(display_frame, orient='horizontal', command=display.xview)
display.config(xscrollcommand=scrollbar.set)
scrollbar.pack(fill='x')

Adding Buttons

Create a grid of buttons inside the button frame. Use a list of button labels and loop through them to create each button. Place them in a 4×4 grid for numbers and operators, plus additional rows for AC, equal sign, etc.

buttons = [
    '7','8','9','/',
    '4','5','6','*',
    '1','2','3','-',
    '0','.','=','+'
]
row_val = 0
col_val = 0
for btn in buttons:
    action = lambda x=btn: click(x)
    tk.Button(button_frame, text=btn, command=action, width=5, height=2).grid(row=row_val, column=col_val, padx=2, pady=2)
    col_val += 1
    if col_val > 3:
        col_val = 0
        row_val += 1
# Add AC button spanning two columns
ac_button = tk.Button(button_frame, text='AC', command=clear, width=12, height=2)
ac_button.grid(row=row_val, column=0, columnspan=2, pady=2)

Adding Functionality

Handling Button Clicks

Define a click function that receives the button label and updates the display. Use a try-except to evaluate the expression when '=' is pressed:

Creating a Functional GUI Calculator with Python's Tkinter
Source: www.freecodecamp.org
def click(value):
    current = display.get()
    if value == '=':
        try:
            result = eval(current)
            display.config(state='normal')
            display.delete(0, tk.END)
            display.insert(tk.END, str(result))
            display.config(state='readonly')
        except:
            display.config(state='normal')
            display.delete(0, tk.END)
            display.insert(tk.END, "Error")
            display.config(state='readonly')
    else:
        display.config(state='normal')
        display.insert(tk.END, value)
        display.config(state='readonly')

Implementing the AC Button

The clear function simply empties the display:

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

Wrapping Up

Now you have a fully functional calculator built with Tkinter. You can extend it by adding memory functions, more advanced operations, or a different color scheme. This project is a perfect starting point for exploring GUI development in Python. Remember to run root.mainloop() to keep the application running.

For more ideas, check out our guide on organizing frames or learn about event handling in Tkinter.

Tags:

Related Articles

Recommended

Discover More

Iran Conflict Exposes Fading Power of U.S. Sanctions, Analysts SayThe Day Canada's 'Emoji Lake' Vanished: A Satellite View of a Catastrophic Bank CollapseStrengthening End-to-End Encrypted Backups: Meta's Latest EnhancementsVacuum Tubes' Final Frontier: Breakthroughs That Defied the Transistor RevolutionMicrosoft Copilot Studio Goes Live with .NET 10 – WebAssembly Upgrade Boosts Speed and Simplifies Deployment