PySimpleGUI is a Python package that allows you to create simple graphical user interfaces (GUI) for your Python applications. In this tutorial, I will show you how to create a basic calculator using PySimpleGUI.
Step 1: Install PySimpleGUI
Before you can start creating your calculator, you will need to install PySimpleGUI. You can do this by running the following command in your terminal:
pip install PySimpleGUI
Step 2: Create a new Python file
Next, create a new Python file in your preferred code editor. You can name the file calculator.py
.
Step 3: Import the necessary modules
In your calculator.py
file, import the PySimpleGUI module as follows:
import PySimpleGUI as sg
Step 4: Create the layout for the calculator
The next step is to define the layout of the calculator. You can use PySimpleGUI elements such as Input
for the display screen and Button
for the calculator buttons. Here is a basic layout for the calculator:
layout = [
[sg.Input(size=(30, 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('0'), sg.Button('.'), sg.Button('='), sg.Button('+')]
]
Step 5: Create the PySimpleGUI window
Now, create a window object using the layout you defined earlier:
window = sg.Window('Calculator', layout)
Step 6: Create the event loop
Next, create a loop that will keep the calculator running until the user closes the window. In this loop, you will handle the events generated when the user interacts with the calculator buttons:
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
Step 7: Implement the calculator logic
In the event loop, you will need to implement the calculator logic to perform arithmetic operations when the user clicks on the calculator buttons. Here is a basic implementation of the calculator logic:
if event in '1234567890':
window['-DISPLAY-'].update(values['-DISPLAY-'] + event)
elif event == '.':
if '.' not in values['-DISPLAY-']:
window['-DISPLAY-'].update(values['-DISPLAY-'] + '.')
elif event == 'C':
window['-DISPLAY-'].update('')
elif event == '=':
try:
result = eval(values['-DISPLAY-'])
window['-DISPLAY-'].update(str(result))
except:
window['-DISPLAY-'].update('ERROR')
Step 8: Close the window
Finally, once the user closes the window, close the PySimpleGUI window object:
window.close()
And that’s it! You have successfully created a simple calculator using PySimpleGUI. You can further customize the calculator by adding more functionality or styling to suit your needs. Feel free to experiment with different layouts and features to create your own custom calculator.