Simple Statistics Calculator - Python GUI with NumPy

Let’s create a simple statistical calculator using the Python NumPy library.








import numpy as np
import tkinter as tk
from tkinter import ttk, messagebox

def calculate_statistics():
    try:
        data = [float(x) for x in entry_data.get().split(',')]
        data_np = np.array(data)

        mean = np.mean(data_np)
        median = np.median(data_np)
        std_dev = np.std(data_np)
        minimum = np.min(data_np)
        maximum = np.max(data_np)

        result_text = f"Mean: {mean:.2f}\n" \
                      f"Median: {median:.2f}\n" \
                      f"Standard Deviation: {std_dev:.2f}\n" \
                      f"Minimum: {minimum:.2f}\n" \
                      f"Maximum: {maximum:.2f}"

        text_result.delete("1.0", tk.END)  # Clear previous results
        text_result.insert(tk.END, result_text)

    except ValueError:
        messagebox.showerror("Error", "Invalid input. Please enter numbers separated by commas.")
    except Exception as e:
        messagebox.showerror("Error", f"An error occurred: {e}")


# --- GUI Setup ---
root = tk.Tk()
root.title("Simple Statistics Calculator")

# Input Label and Entry
label_data = ttk.Label(root, text="Enter numbers (comma-separated):")
label_data.pack(pady=5)

entry_data = ttk.Entry(root, width=40)
entry_data.pack(pady=5)

# Calculate Button
button_calculate = ttk.Button(root, text="Calculate", command=calculate_statistics)
button_calculate.pack(pady=10)

# Result Text Area
label_result = ttk.Label(root, text="Results:")
label_result.pack(pady=5)

text_result = tk.Text(root, height=10, width=40)
text_result.pack(pady=5)

root.mainloop()

-
Explanation :

This Python script creates a simple statistics calculator using the NumPy library and a graphical user interface (GUI) built with Tkinter. Here's a breakdown of the code:

  1. Import Libraries:
    • numpy as np: Imports the NumPy library for numerical operations.
    • tkinter as tk: Imports the Tkinter library for creating the GUI.
    • tkinter.ttk: Imports themed Tkinter widgets for a more modern look.
    • tkinter.messagebox: Imports the messagebox module for displaying error messages.
  2. calculate_statistics() Function:
    • This function is called when the "Calculate" button is clicked.
    • Input Handling: It retrieves the comma-separated numbers from the entry_data widget.
    • Data Conversion: It attempts to convert the input string into a list of floating-point numbers using a list comprehension.
    • NumPy Array Creation: It creates a NumPy array (data_np) from the list of numbers.
    • Statistical Calculations: It uses NumPy functions to calculate the mean (np.mean()), median (np.median()), standard deviation (np.std()), minimum (np.min()), and maximum (np.max()) of the data.
    • Result Display: It formats the results into a string and displays them in the text_result widget.
    • Error Handling: It includes try...except blocks to handle potential errors:
      • ValueError: Catches errors if the user enters invalid input (e.g., non-numeric characters).
      • Exception: Catches any other unexpected errors. Error messages are displayed using messagebox.showerror().
  3. GUI Setup:
    • Root Window: Creates the main application window (root).
    • Widgets: Creates the following widgets:
      • label_data: A label to prompt the user to enter data.
      • entry_data: An entry field where the user enters the numbers.
      • button_calculate: A button that triggers the calculate_statistics() function.
      • label_result: A label to indicate the results area.
      • text_result: A text area to display the calculated statistics.
    • Layout: Uses the pack() geometry manager to arrange the widgets in the window. pady adds vertical padding for better spacing.
    • Main Loop: Starts the Tkinter event loop (root.mainloop()), which listens for user interactions and keeps the window open.

How to Run on Windows:

  1. Save the Code: Save the code as a .py file (e.g., statistics_calculator.py).
  2. Install Libraries: If you don't have them already, install NumPy and Tkinter using pip:



pip install numpy

(Tkinter usually comes pre-installed with Python on Windows, but if not, you might need to install the python-tk package.)
    
    3. Run the Script: Open a command prompt or terminal, navigate to the directory where you saved the file, and run the script:


python statistics_calculator.py

This will open a window with the statistics calculator. Enter numbers separated by commas, click "Calculate," and the results will be displayed in the text area.

Comments