👉🏻Master Math Magic: Make a Calculator... 🧮✨

Build a Simple Calculator with PySimpleGUI!

 

Welcome back, CodeCrafters! 🎉

In our last post, we explored the amazing world of PySimpleGUI themes.

Today, we’re going to take things up a notch and create a simple calculator app using PySimpleGUI.

This step-by-step guide will make the learning fun, friendly, and super engaging.

Ready to dive in?

Let’s get calculating!

 

Step 1: Setting Up Your Environment

First things first, let’s make sure you have PySimpleGUI installed. If you haven’t already, open your terminal or command prompt and type:

pip install pysimplegui

 

Step 2: Import the Necessary Libraries

We’ll start by importing the libraries we need for our calculator app:

import PySimpleGUI as sg

 

Step 3: Define the Layout

Next, we’ll define the layout of our calculator. This will include buttons for digits (0-9), operations (+, -, *, /), and other necessary buttons like ‘=’ and ‘C’ (clear):

 

layout = [

    [sg.Text('', size=(20, 1), justification='right', key='-DISPLAY-')],

    [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('+')],

    [sg.Button('C'), sg.Button('←')]

]

Simple Calculator

Step 4: Create the Window

We’ll create the window using the layout we just defined. The window will have a title and a theme for a nice look:

 

sg.theme('DarkAmber')  # You can choose any theme you like

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

 

Step 5: Define the Event Loop

The event loop is where all the magic happens. We’ll handle button clicks and perform the calculations here:

 

current_input = ''

while True:

    event, values = window.read()

 

    if event == sg.WINDOW_CLOSED:

        break

 

    if event in '0123456789':

        current_input += event

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

 

    elif event in '+-*/':

        current_input += ' ' + event + ' '

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

 

    elif event == '=':

        try:

            result = eval(current_input)

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

            current_input = str(result)

        except:

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

            current_input = ''

 

    elif event == 'C':

        current_input = ''

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

 

    elif event == '←':

        current_input = current_input[:-1]

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

 

    elif event == '.':

        current_input += event

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

 

Step 6: Closing the Window

Finally, we need to close the window properly:

window.close()

Understanding the eval() Function in Our Calculator Code

 

In our simple calculator app, we used the eval() function to perform the calculations. Let’s break down what eval() does and why it’s useful in this context.

 

What is eval()?

The eval() function in Python takes a string as an argument and evaluates it as a Python expression. This means it can execute any valid Python code within the string and return the result.

 

Here’s a basic example:

result = eval('2 + 3 * 4')

print(result)  # Output: 14

 

In this example, eval() evaluates the string '2 + 3 * 4' as a mathematical expression and returns the result, which is 14.

 

How We Used eval() in Our Calculator

In our calculator code, we used eval() to evaluate the mathematical expression entered by the user. Let’s look at the relevant part of the code:

 

if event == '=':

    try:

        result = eval(current_input)

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

        current_input = str(result)

    except:

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

        current_input = ''

 

Step-by-Step Explanation

  1. User Input: As the user clicks buttons, the corresponding characters (digits, operators) are appended to the current_input string.

  2. Equal Button Clicked: When the user clicks the '=' button, the calculator needs to evaluate the mathematical expression stored in current_input.

  3. Using eval(): The eval(current_input) line takes the string current_input (which looks something like '2 + 3 * 4') and evaluates it as a Python expression.

  4. Displaying the Result: The result of eval(current_input) is stored in the result variable. This result is then displayed in the calculator's output display using window['-DISPLAY-'].update(result).

  5. Handling Errors: If there’s an error in the expression (for example, if the user entered an incomplete expression like '2 + '), the eval() function will raise an exception. We catch this exception with a try...except block and display 'Error' on the calculator's display instead.

 

Why eval() is Useful

  • Flexibility: eval() allows the calculator to handle any valid mathematical expression entered by the user, without needing to manually parse and compute the expression.

  • Simplicity: It simplifies the code by leveraging Python's built-in capabilities to evaluate expressions, making our code cleaner and easier to understand.

 

Important Note

While eval() is powerful, it should be used with caution, especially with untrusted input, because it can execute arbitrary code. In our simple calculator app, the input is controlled and limited to basic arithmetic operations, making it safe for this use case.

78 + 6 = ?

78 + 6 = 84

Let’s Sum It Up!

In this post, we built a simple yet functional calculator using PySimpleGUI. We covered how to set up the environment, define the layout, create the window, and handle events to make our calculator work.

The fun part?

You can now perform basic arithmetic operations right from your custom-built GUI calculator!

Looking to supercharge your startup journey with insights, stories, and vibes that resonate with the tech and entrepreneurial spirit? Subscribe to Big Desk Energy at this link for a fresh dose of inspiration and practical tips to fuel your ambitions. Don’t miss out on the best startup content around – join now and take your entrepreneurial game to the next level!

Let’s Inspire Future AI Coders Together! ☕

 

I’m excited to continue sharing my passion for Python programming and AI with you all. If you’ve enjoyed the content and found it helpful, do consider supporting my work with a small gift. Just click the link below to make a difference – it’s quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.

Thank you for being amazing!

What’s Next? 📅

Stay tuned for our next exciting post where we’ll dive into even more cool GUI elements and continue building amazing applications with PySimpleGUI!🚀👩‍💻

Ready for More Python Fun? 📬

Subscribe to our newsletter now and get a free Python cheat sheet! 📑 Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.

Keep learning, keep coding 👩‍💻👨‍💻, and keep discovering new possibilities! 💻

Enjoy your journey into artificial intelligence, machine learning, data analytics, data science and more with Python!

Stay tuned for our next exciting project in the following edition!

Happy coding!🚀📊✨

🎉 We want to hear from you! 🎉 How do you feel about our latest newsletter? Your feedback will help us make it even more awesome!

Login or Subscribe to participate in polls.