Computer Programming 2 - Task 1

Building a Simple GUI Calculator with Virtual Environments

Introduction & Objectives

Welcome to your first lab for Computer Programming 2! In this lab, we will combine the concepts of virtual environments and dependency management with practical programming. You will build a simple calculator with a graphical user interface (GUI).

By the end of this lab, you will be able to:

Materials Required

Lab Procedure

Follow these steps carefully. Each step builds upon the previous one.

Learning Outcome 1: The initial steps of this lab address your ability to analyse an engineering application to facilitate the development of a software solution using rapid application development (RAD) techniques.

By setting up the project structure and identifying the necessary libraries, you perform an analysis to establish software requirements for this engineering application (the GUI calculator). Creating the `requirements.txt` file provides a structured interpretation of the application requirements for dependencies, which is a key part of the analysis process.

  1. Step 1: Create a Project Directory

    First, let's create a dedicated folder for our project. This helps keep all our files organized.

    Open your command line interface and create a new directory called calculator-project, then navigate into it.

    mkdir calculator-project
    cd calculator-project
  2. Step 2: Create the Virtual Environment

    Inside your project directory, create a virtual environment. We will name our environment venv. This command creates a new folder named venv containing a private copy of Python and pip.

    python -m venv venv
    Note: If you have multiple Python versions, you might need to use python3 instead of python. For example: python3 -m venv venv.
  3. Step 3: Activate the Virtual Environment

    To use the virtual environment, you must "activate" it. The command differs based on your operating system.

    On Windows (Command Prompt/PowerShell):

    venv\Scripts\activate

    On macOS or Linux:

    source venv/bin/activate

    Once activated, you will see the name of your virtual environment in parentheses at the beginning of your command prompt, like this: (venv) C:\Users\YourUser\calculator-project>. This indicates that any Python commands or package installations will be confined to this environment.

  4. Step 4: Install a Dependency (PySimpleGUI)

    Our calculator needs a GUI. We will use a beginner-friendly library called PySimpleGUI. We install it using pip, Python's package installer. Because our virtual environment is active, this library will be installed only within venv, not globally on your computer.

    pip install PySimpleGUI

    You should see output indicating that the package was successfully installed.

  5. Step 5: Create a `requirements.txt` File

    It's a best practice to keep a record of your project's dependencies. This allows other developers (or you, on a different machine) to easily install the exact same packages. We can do this automatically.

    Run the following command to save all installed packages in the current environment to a file named requirements.txt.

    pip freeze > requirements.txt

    If you open this new file, you will see PySimpleGUI and its version listed.

  6. Learning Outcome 2: The following step addresses your ability to develop a software solution for an engineering application using RAD techniques.

    You will now develop the software solution by writing the Python code. This task is a practical demonstration of how to apply RAD tools and components (`PySimpleGUI`) to make effective and efficient use of the library's RAD tool capabilities to quickly build the GUI.

  7. Step 6: Write the Calculator Code

    Now it's time to write the code! Create a new file named calculator_app.py inside your calculator-project directory. Open it in your code editor and type or paste the following code.

    Read the comments in the code to understand how it works.

    # Import the PySimpleGUI library and give it a shorter alias 'sg'
    import PySimpleGUI as sg
    
    # Set a theme for the GUI window
    sg.theme('DarkTeal9')
    
    # Define the layout of the calculator. It's a list of lists, where each inner list is a row.
    layout = [
        # Row 1: The display screen for numbers and results. It's an Input element.
        # It's read-only, has a default text of '0', and is right-justified.
        [sg.Input(size=(20, 1), font=('Helvetica', 20), justification='right', key='-DISPLAY-', readonly=True)],
        
        # Row 2: Buttons for Clear (C), Parentheses (), Percentage (%), and Division (/)
        [sg.Button('C', size=(4,2)), sg.Button('(', size=(4,2)), sg.Button(')', size=(4,2)), sg.Button('/', size=(4,2))],
        
        # Row 3: Buttons for numbers 7, 8, 9 and Multiplication (*)
        [sg.Button('7', size=(4,2)), sg.Button('8', size=(4,2)), sg.Button('9', size=(4,2)), sg.Button('*', size=(4,2))],
        
        # Row 4: Buttons for numbers 4, 5, 6 and Subtraction (-)
        [sg.Button('4', size=(4,2)), sg.Button('5', size=(4,2)), sg.Button('6', size=(4,2)), sg.Button('-', size=(4,2))],
        
        # Row 5: Buttons for numbers 1, 2, 3 and Addition (+)
        [sg.Button('1', size=(4,2)), sg.Button('2', size=(4,2)), sg.Button('3', size=(4,2)), sg.Button('+', size=(4,2))],
        
        # Row 6: Button for number 0 (spans two columns), a decimal point (.), and the Equals (=) button
        [sg.Button('0', size=(9,2)), sg.Button('.', size=(4,2)), sg.Button('=', size=(4,2))],
    ]
    
    # Create the window using the defined layout
    window = sg.Window('Simple Calculator', layout)
    
    # --- Main Application Logic ---
    current_expression = ''
    
    # Event loop to process "events" and get the "values" of the inputs
    while True:
        event, values = window.read()
    
        # If user closes window or clicks cancel, break the loop
        if event == sg.WIN_CLOSED:
            break
    
        # If the user clicks the 'C' (Clear) button
        if event == 'C':
            current_expression = ''
            window['-DISPLAY-'].update('0')
    
        # If the user clicks the '=' (Equals) button
        elif event == '=':
            try:
                # 'eval' is a powerful but potentially risky function. 
                # It evaluates a string as a Python expression.
                # Here, it's safe because we control the input.
                result = eval(current_expression)
                window['-DISPLAY-'].update(result)
                current_expression = str(result)
            except Exception as e:
                # If an error occurs (e.g., division by zero), show 'Error'
                window['-DISPLAY-'].update('Error')
                current_expression = ''
    
        # For any other button press (numbers or operators)
        else:
            # Append the button's text to our expression string
            current_expression += event
            window['-DISPLAY-'].update(current_expression)
    
    # Close the window when the loop is broken
    window.close()
    
  8. Step 7: Run Your GUI Application

    Save your calculator_app.py file. Make sure your virtual environment is still active in your command line, and then run the script:

    python calculator_app.py

    If everything is correct, your simple calculator application should appear on the screen! Test it out by performing some calculations.

  9. Step 8: Deactivate the Virtual Environment

    Once you are finished working on your project, you can deactivate the virtual environment. This returns your command line to its normal state.

    Simply type the following command:

    deactivate

    The (venv) prefix will disappear from your command prompt.

Evaluation and Reflection

Learning Outcome 3: This final task addresses your ability to evaluate the performance of a RAD software solution to an engineering application.

To complete this, you must technically appraise the performance of your application and use informed judgement to identify potential software solution deficiencies. Finally, the results are evaluated to identify areas for improvement.

Answer the following questions in a separate document. Your answers should be concise but thorough.

  1. Appraise Performance: Test your calculator by attempting to divide a number by zero (e.g., 8/0). Describe what happens. The code includes a try...except block to handle this. Explain if this is an effective way to handle errors or if it's a software solution deficiency. Why?
  2. Identify Deficiencies: The code uses the eval() function for calculation. Research the `eval()` function in Python. Based on your findings and using your informed judgement, explain why using eval() can be a significant risk and a critical deficiency in a real-world application. What is the potential danger?
  3. Identify Areas for Improvement: Based on the deficiency identified in the previous question, suggest an alternative approach to parsing and calculating the expression instead of using `eval()`. You do not need to write the code; instead, describe the logic of how you would process the input string to get a result. This is a key step where the results are evaluated to identify areas for improvement.

Lab Submission

To complete the lab, please submit the following files:

Troubleshooting

Problem: The command python -m venv venv gives an error like "command not found".

Solution: This means Python is not correctly added to your system's PATH. Try using python3 instead of python. If that still fails, you may need to reinstall Python, ensuring you check the "Add Python to PATH" option during installation.

Problem: When I run python calculator_app.py, I get a ModuleNotFoundError: No module named 'PySimpleGUI'.

Solution: This almost always means your virtual environment is not active. Look for the (venv) prefix in your command prompt. If it's not there, run the activation command from Step 3 again.