Skip to main content

Python Calculator Program with GUI Intercface

 


 Python Calculator Program with GUI Intercface

Here is a Python program using the tkinter library to create a simple GUI-based calculator. This calculator can perform basic arithmetic operations like addition, subtraction, multiplication, and division.

 

import tkinter as tk

# Function to update the input field when a button is clicked
def button_click(item):
    global expression
    expression = expression + str(item)
    input_text.set(expression)

# Function to clear the input field
def button_clear():
    global expression
    expression = ""
    input_text.set("")

# Function to evaluate the expression and display the result
def button_equal():
    global expression
    try:
        result = str(eval(expression))  # Evaluate the expression
        input_text.set(result)
        expression = result
    except:
        input_text.set("Error")
        expression = ""

# Create the main window
root = tk.Tk()
root.title("Simple Calculator")
root.geometry("300x400")
root.resizable(0, 0)

# Global variable to store the expression
expression = ""

# StringVar to store the input and output
input_text = tk.StringVar()

# Create an input frame
input_frame = tk.Frame(root, width=312, height=50, bd=0, highlightbackground="black", highlightcolor="black", highlightthickness=1)
input_frame.pack(side=tk.TOP)

# Create an input field inside the input frame
input_field = tk.Entry(input_frame, font=('arial', 18, 'bold'), textvariable=input_text, width=50, bg="#eee", bd=0, justify=tk.RIGHT)
input_field.grid(row=0, column=0)
input_field.pack(ipady=10)  # Internal padding to increase the height

# Create a button frame
button_frame = tk.Frame(root, width=312, height=272.5, bg="grey")
button_frame.pack()

# First row of buttons
clear = tk.Button(button_frame, text="C", fg="black", width=32, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_clear())
clear.grid(row=0, column=0, columnspan=3)

divide = tk.Button(button_frame, text="/", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_click("/"))
divide.grid(row=0, column=3)

# Second row of buttons
seven = tk.Button(button_frame, text="7", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(7))
seven.grid(row=1, column=0)

eight = tk.Button(button_frame, text="8", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(8))
eight.grid(row=1, column=1)

nine = tk.Button(button_frame, text="9", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(9))
nine.grid(row=1, column=2)

multiply = tk.Button(button_frame, text="*", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_click("*"))
multiply.grid(row=1, column=3)

# Third row of buttons
four = tk.Button(button_frame, text="4", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(4))
four.grid(row=2, column=0)

five = tk.Button(button_frame, text="5", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(5))
five.grid(row=2, column=1)

six = tk.Button(button_frame, text="6", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(6))
six.grid(row=2, column=2)

subtract = tk.Button(button_frame, text="-", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_click("-"))
subtract.grid(row=2, column=3)

# Fourth row of buttons
one = tk.Button(button_frame, text="1", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(1))
one.grid(row=3, column=0)

two = tk.Button(button_frame, text="2", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(2))
two.grid(row=3, column=1)

three = tk.Button(button_frame, text="3", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(3))
three.grid(row=3, column=2)

add = tk.Button(button_frame, text="+", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_click("+"))
add.grid(row=3, column=3)

# Fifth row of buttons
zero = tk.Button(button_frame, text="0", fg="black", width=21, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda: button_click(0))
zero.grid(row=4, column=0, columnspan=2)

point = tk.Button(button_frame, text=".", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_click("."))
point.grid(row=4, column=2)

equals = tk.Button(button_frame, text="=", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda: button_equal())
equals.grid(row=4, column=3)

# Run the application
root.mainloop() 

 

How the Program Works

Input Field:

The input field displays the numbers and operators as they are clicked.

It also displays the result after evaluation.

Buttons:


Buttons for digits (0-9), operators (+, -, *, /), and special functions (clear, equals) are created.

Each button is linked to a function that updates the input field or evaluates the expression.

Functions:

button_click(item): Appends the clicked button's value to the expression.

button_clear(): Clears the input field.

button_equal(): Evaluates the expression and displays the result.

Error Handling:

If an invalid expression is entered (e.g., division by zero), the program displays "Error".

How to Run:
Save the code to a file, e.g., calculator.py.

Run the file using Python: python calculator.py.

Use the GUI to perform calculations.

This is a simple and functional calculator that can be expanded with additional features if needed!

Comments

Popular posts from this blog

Python GUI Program to Calculate Age

Python GUI Program to Calculate Age     Certainly! Below is a Python program using the tkinter library to create a simple GUI that accepts a date of birth and calculates the age.   import tkinter as tk from tkinter import messagebox from datetime import datetime def calculate_age():     dob_str = entry_dob.get()     try:         dob = datetime.strptime(dob_str, "%Y-%m-%d")         today = datetime.today()         age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))         messagebox.showinfo("Age Calculator", f"Your age is: {age} years")     except ValueError:         messagebox.showerror("Error", "Please enter the date in YYYY-MM-DD format") # Create the main window root = tk.Tk() root.title("Age Calculator") # Create a labe...

Classic Number Guessing Game Using Python

    Build Your First Python Game: The Classic Number Guessing Game! Are you learning Python and looking for a fun, hands-on project to test your skills? You’ve come to the right place. When starting out with programming, it’s easy to get stuck just reading tutorials. The real magic happens when you build something interactive. Today, we’re going to build a classic: The Number Guessing Game . It’s simple concept: The computer picks a random number between 1 and 100, and you have a limited number of tries to guess it. After every guess, the computer tells you if you need to go "Higher" or "Lower." Why This is the Perfect Beginner Project Despite its simplicity, this game is a fantastic learning tool because it combines several fundamental programming concepts into one cohesive package. By building this, you will master: Variables: Storing information like the secret number and attempts left. Loops ( while ): Keeping the game running until the player wins or loses. C...