Create a GUI calculator using PySimpleGUI in Python

Posted by


In this tutorial, we will be creating a simple GUI calculator using Python and the PySimpleGUI library. PySimpleGUI is a simple-to-use framework for creating GUIs in Python, and it is especially well-suited for beginners.

To get started, you will need to have Python and PySimpleGUI installed on your machine. You can install PySimpleGUI using pip by running the following command in your terminal:

pip install PySimpleGUI

Once you have PySimpleGUI installed, you can start creating your GUI calculator. Here is the code for a simple calculator interface using PySimpleGUI:

import PySimpleGUI as sg

layout = [
    [sg.Input(size=(25,1), key='-DISPLAY-', justification='right')],
    [sg.Button('7'), sg.Button('8'), sg.Button('9'), sg.Button('+')],
    [sg.Button('4'), sg.Button('5'), sg.Button('6'), sg.Button('-')],
    [sg.Button('1'), sg.Button('2'), sg.Button('3'), sg.Button('*')],
    [sg.Button('C'), sg.Button('0'), sg.Button('='), sg.Button('/')]
]

window = sg.Window('Simple Calculator', layout)

display = ''

while True:
    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

    if event == 'C':
        display = ''

    elif event == '=':
        try:
            display = str(eval(display))
        except:
            display = 'Error'

    else:
        display += event

    window['-DISPLAY-'].update(display)

window.close()

This code creates a simple calculator interface with buttons for the numbers 0-9 as well as the basic arithmetic operators (+, -, *, /). The user can input numbers and perform calculations, and the result will be displayed in the input field at the top.

To run this code, simply save it to a Python file (e.g., calculator.py) and run it using the Python interpreter. You should see a window pop up with the calculator interface, and you can start using it to perform calculations.

With PySimpleGUI, you can easily customize the appearance and functionality of your GUI calculator by adding more buttons, changing the layout, or adding additional features like memory functions or scientific calculator functions.

Overall, PySimpleGUI is a great tool for creating GUI applications in Python, especially for beginners who are new to GUI programming. I hope this tutorial helps you get started with creating your own Python GUI calculator using PySimpleGUI.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@carltarder2193
1 month ago

you are my new favorite person