Build a Simple Python Calculator with PySimpleGUI – Step-by-Step Guide

Learn how to create a lightweight calculator using Python's PySimpleGUI library, complete with basic arithmetic operations, history tracking, clear and delete functions, and a user-friendly interface, all demonstrated through a full, runnable code example.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Build a Simple Python Calculator with PySimpleGUI – Step-by-Step Guide

Introduction

Hello, I am a Python enthusiast. This article shares a simple calculator built with the PySimpleGUI library, ideal for beginners who want to explore GUI development in Python.

Implementation

Below is the complete source code for the calculator:

import PySimpleGUI as sg

# Define the main window layout

def window_main():
    layout = [
        [sg.Text('计算结果:', font=("微软雅黑", 10)), sg.Button('历史记录', font=("微软雅黑", 10), pad=(10, 1))],
        [sg.Text('0', key='-express-', justification='right', size=(30, 1), font=("微软雅黑", 10), background_color='#fff', text_color='#000')],
        [sg.Text('0', key='-result-', justification='right', size=(30, 1), font=("微软雅黑", 10), background_color='#fff', text_color='#000')],
        [sg.Button('清空', size=(6, 2)), sg.Button('删除', size=(6, 2)), sg.Button('x²', size=(6, 2)), sg.Button('÷', size=(6, 2))],
        [sg.Button('7', size=(6, 2)), sg.Button('8', size=(6, 2)), sg.Button('9', size=(6, 2)), sg.Button('x', size=(6, 2))],
        [sg.Button('4', size=(6, 2)), sg.Button('5', size=(6, 2)), sg.Button('6', size=(6, 2)), sg.Button('-', size=(6, 2))],
        [sg.Button('1', size=(6, 2)), sg.Button('2', size=(6, 2)), sg.Button('3', size=(6, 2)), sg.Button('+', size=(6, 2))],
        [sg.Button('+/-', size=(6, 2)), sg.Button('0', size=(6, 2)), sg.Button('.', size=(6, 2)), sg.Button('=', size=(6, 2))],
    ]
    return sg.Window('简易计算器@月亮', layout, finalize=True, default_element_size=(50, 1))

# Define the history window layout

def createwindow_history(history_list=None):
    history_text = ''
    if history_list:
        history_text = '
'.join(['='.join(i) for i in history_list])
    layout = [
        [sg.Text('历史记录:', font=("微软雅黑", 10))],
        [sg.Multiline(history_text, justification='right', disabled=True, autoscroll=True, size=(30, 10), font=("微软雅黑", 10), background_color='#fff', text_color='#000')]
    ]
    return sg.Window('历史记录', layout, finalize=True)


def get_result(eval_str):
    global result
    eval_str = eval_str.replace('^', '**').replace('x', '*').replace('÷', '/')
    try:
        result = eval(eval_str)
    except Exception:
        result = '0'
    window_main['-result-'].update(result)
    return str(result)

window_main = window_main()
window_sub = None
history_list = []
express = '0'
result = '0'
flag = 0

while True:
    window, event, value = sg.read_all_windows()
    if window == window_main and event in (None, sg.WIN_CLOSED):
        if window_sub is not None:
            window_sub.close()
        break
    elif event == '历史记录':
        if not window_sub:
            window_sub = createwindow_history(history_list)
        else:
            window_sub.close()
            window_sub = None
    elif window == window_sub and event is None:
        window_sub.close()
        window_sub = None
    elif event == '=':
        express1 = express
        express = get_result(express)
        history_list.append([express1, express])
        flag = 1
    elif event == '清空':
        express = '0'
        result = '0'
        window_main['-express-'].update(express)
        window_main['-result-'].update(result)
    elif event == '删除':
        if len(express.lstrip('-').strip('(').strip(')')) == 1:
            express = '0'
        elif express[-1] == ')':
            express = express.lstrip('-').strip('(').strip(')')
        else:
            express = express[:-1]
        window_main['-express-'].update(express)
    elif event == 'x²':
        express = f'({express}) ^ 2'
        window_main['-express-'].update(express)
    elif event == '+/-':
        express = f'-({express})'
        get_result(express)
    else:
        if flag == 1 and event in '0123456789':
            express = '0'
            flag = 0
        if express == '0':
            express = event
        else:
            express = express + event
        window_main['-express-'].update(express)

window.close()

Running the script displays a functional calculator window.

You can perform basic addition, subtraction, multiplication, and division, as well as clear entries and view calculation history.

Conclusion

This tutorial demonstrates how to build a lightweight calculator with PySimpleGUI, covering UI layout, event handling, expression evaluation, and history management, providing a solid foundation for further GUI projects in Python.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GUIcodeCalculatorpysimplegui
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.