SoFunction
Updated on 2025-03-03

Python uses PySimpleGUI to create a lightweight calculator

In the Python world, there are a variety of options for GUI (Graphical User Interface) libraries, but if you are a newbie or want to create a GUI application quickly and simply, then PySimpleGUI is undoubtedly an excellent choice. PySimpleGUI is a Python module for creating simple and easy-to-use graphical user interfaces (GUIs), which provides a clean API that enables developers to quickly build interfaces without too much attention to complex details.

In this article, we will use the PySimpleGUI library together to create a lightweight calculator. Through this process, you will learn about the basic operations of PySimpleGUI, the use of components, event processing, and layout management.

1. Introduction to PySimpleGUI

PySimpleGUI is a cross-platform Python GUI library that supports a variety of operating systems such as Windows, Mac and Linux. The original intention of this library is to enable developers to create powerful GUI applications with as little code as possible. The PySimpleGUI API is designed to be very intuitive and concise, making it easy for even newbies to get started.

The main features of PySimpleGUI include:

  • You can add common GUI components such as buttons, text boxes, and labels.
  • Supports setting the style and appearance of components.
  • Provides an event handling mechanism to bind callback functions to components.
  • Supports layout management, allowing for flexible arrangement and resizing of components.

2. Install PySimpleGUI

First, you need to install the PySimpleGUI library. You can use pip to install:

pip install pysimplegui

3. Create a calculator interface

Before creating a calculator interface, we need to plan the layout and functions of the calculator first. A basic calculator usually includes a number button, an operator button, an equals button, and a text box that displays the results.

Here is a simple example of creating a calculator interface using PySimpleGUI:

import PySimpleGUI as sg  
  
# Define the layout of the windowlayout = [  
    [('Calculator', size=(20, 1), justification='center', font=("Helvetica", 25))],  
    [(size=(20, 1), enable_events=True, key='-INPUT-')],  
    [('7'), ('8'), ('9'), ('/')],  
    [('4'), ('5'), ('6'), ('*')],  
    [('1'), ('2'), ('3'), ('-')],  
    [('0'), ('.'), ('+'), ('=')],  
    [('C')]  
]  
  
# Create a windowwindow = ('Calculator', layout)  
  
# Event loopwhile True:  
    event, values = ()  
    if event == sg.WIN_CLOSED or event == 'C':  # If the window's close button or 'C' button is clicked        break  
    print('You entered ', values['-INPUT-'])  # Print the contents of the input box  
()

In the above code, we first define a layout layout that describes the various components of the calculator and their location. We then created a window using it and passed the layout to it. Finally, we enter an event loop, constantly reading the user's events and inputs, and performing corresponding operations based on the events.

4. Implement the functions of the calculator

Now that we have the interface of the calculator, we need to implement the functions of the calculator next. To achieve this function, we need to bind the callback function for the numeric button and operator button, and process the corresponding calculation logic in the callback function.

Here is a sample code that implements the basic functions of the calculator:

import PySimpleGUI as sg  
import operator  
  
# Define operators and their corresponding functionsoperators = {  
    '+': ,  
    '-': ,  
    '*': ,  
    '/':   
}  
  
# Initialize the calculator's statuscalculator = {  
    'result': 0,  
    'operation': None,  
    'operand': None  
}  
  
# Define the calculator's callback functiondef evaluate(event, values, calculator):  
    if calculator['operation'] is None:  
        calculator['operand'] = float(values['-INPUT-'])  
        calculator['operation'] = operators[event]  
        window['-INPUT-'].update('')  
    else:  
        calculator['result'] = calculator['operation'](calculator['result'], float(values['-INPUT-']))  
        calculator['operation'] = None  
        window['-INPUT-'].update(str(calculator['result']))  
  
def clear(event, values, calculator):  
    calculator['result'] = 0  
    calculator['operation'] = None  
    calculator['operand'] = None  
    window['-INPUT-'].update
 
 
 
 
#Define the layout of the windowlayout = [
[('Calculator', size=(20, 1), justification='center', font=("Helvetica", 25))],
[(size=(20, 1), enable_events=True, key='-INPUT-')],
[('7', key='7'), ('8', key='8'), ('9', key='9'), ('/', key='/')],
[('4', key='4'), ('5', key='5'), ('6', key='6'), ('', key='')],
[('1', key='1'), ('2', key='2'), ('3', key='3'), ('-', key='-')],
[('0', key='0'), ('.', key='.'), ('+', key='+'), ('=', key='=')],
[('C', key='C')]
]
 
#Create a windowwindow = ('Calculator', layout)
 
Event loop
while True:
event, values = ()
if event == sg.WIN_CLOSED or event == 'C':
break
elif event in operators:
evaluate(event, values, calculator)
elif event == '=':
if calculator['operation'] is not None:
calculator['result'] = calculator['operation'](calculator['result'], float(values['-INPUT-']))
window['-INPUT-'].update(str(calculator['result']))
calculator['operation'] = None
elif () or event == '.':
if calculator['operation'] is None:
window['-INPUT-'].update(window['-INPUT-'].get() + event)
else:
print('Please complete the previous operation first.')
 
()

In the above code, we define an evaluate function to handle click events for numeric buttons and operator buttons. When the user clicks a numeric button, we add the number to the input box; when the user clicks an operator button, we save the current result and operator, clear the input box, and wait for the input of the next operand. When the user clicks the equal sign button, we perform the corresponding calculation and update the result to the input box. In addition, we have added a clear button to clear the state of the calculator.

5. Summary

With the above sample code, we show how to create a lightweight calculator application using the PySimpleGUI library. Although the functionality of this calculator is relatively simple, it covers the basic usage of the PySimpleGUI library, including creating windows, adding components, handling events, and updating interfaces. With this example, you can further learn and explore other features and usages of the PySimpleGUI library to create more complex and practical GUI applications.

The PySimpleGUI library provides Python developers with a simple and powerful GUI development tool. Through learning and practice, you can quickly build a variety of beautiful and powerful GUI applications using this library.

This is the article about Python using PySimpleGUI to create a lightweight calculator. For more related content of Python PySimpleGUI, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!