Simple calculator using button widgets

 import tkinter as tk

from tkinter import messagebox


def calculate():

    try:

        num1 = float(entry_num1.get())

        num2 = float(entry_num2.get())

        operation = operation_var.get()

        

        if operation == "+":

            result = num1 + num2

        elif operation == "-":

            result = num1 - num2

        elif operation == "*":

            result = num1 * num2

        elif operation == "/":

            if num2 == 0:

                messagebox.showerror("Error", "Cannot divide by zero!")

                return

            else:

                result = num1 / num2

        else:

            messagebox.showerror("Error", "Invalid operation!")

            return

        

        result_label.config(text="Result: " + str(result))

    except ValueError:

        messagebox.showerror("Error", "Invalid input! Please enter numbers.")


def clear():

    entry_num1.delete(0, tk.END)

    entry_num2.delete(0, tk.END)

    result_label.config(text="Result: ")


# Create the main application window

root = tk.Tk()

root.title("Simple Calculator")


# Entry fields for inputting numbers

entry_num1 = tk.Entry(root, width=10)

entry_num1.grid(row=0, column=0)


entry_num2 = tk.Entry(root, width=10)

entry_num2.grid(row=0, column=1)


# Operation selection dropdown menu

operation_var = tk.StringVar(root)

operation_var.set("+")  # Default operation is addition

operation_menu = tk.OptionMenu(root, operation_var, "+", "-", "*", "/")

operation_menu.grid(row=0, column=2)


# Buttons for calculate and clear

calculate_button = tk.Button(root, text="Calculate", command=calculate)

calculate_button.grid(row=1, column=0, columnspan=5)


clear_button = tk.Button(root, text="Clear", command=clear)

clear_button.grid(row=1, column=2)


# Label to display the result

result_label = tk.Label(root, text="Result: ")

result_label.grid(row=2, column=0, columnspan=3)


# Run the Tkinter event loop

root.mainloop()


Comments