INTRODUCTION
The BASIC_CALCULATOR in Python is a simple GUI-primarily based calculator constructed the usage of Tkinter. It lets in customers to perform primary arithmetic operations which includes addition, subtraction, multiplication, and department. This task facilitates in knowledge GUI improvement in Python, event handling, and operating with Tkinter widgets.
Step 1: Import Tkinter: The program imports the tkinter
module to create the GUI interface.
import tkinter as tk
STEP 2: Define Button Click Function: The button_click() characteristic inserts the clicked range or operator into the entry discipline.
def button_click(number): entry_field.insert(tk.END, number)
STEP 3: Define Calculation Function: The calculate() feature evaluates the entered mathematical expression using eval() and displays the end result.
def calculate(): try: result = eval(entry_field.get()) entry_field.delete(0, tk.END) entry_field.insert(tk.END, str(result)) except Exception: entry_field.delete(0, tk.END) entry_field.insert(tk.END, "Error")
Step 4: Define Clear Function: The clear()
function clears the entry field when the user presses “C”.
def clear(): entry_field.delete(0, tk.END)
STEP 5: Create Main Window: A Tkinter window (root) is created and titled “Basic Calculator.”
root = tk.Tk() root.title("Basic Calculator")
Step 6: Create Entry Field: The program adds an entry widget to display user input and results.
entry_field = tk.Entry(root, width=20, font=("Arial", 18), bd=5, relief="ridge", justify="right") entry_field.grid(row=0, column=0, columnspan=4)
Step 7: Define Button Layout: The program creates a list of button labels and positions for the calculator’s number pad and operators.
buttons = [ ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3), ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3), ('0', 4, 0), ('C', 4, 1), ('=', 4, 2), ('+', 4, 3) ]
STEP 8: Create Buttons: The program iterates thru the button listing, growing buttons and putting them in the grid format.
for text, row, col in buttons: if text == "=": btn = tk.Button(root, text=text, width=5, height=2, font=("Arial", 14), command=calculate) elif text == "C": btn = tk.Button(root, text=text, width=5, height=2, font=("Arial", 14), command=clear) else: btn = tk.Button(root, text=text, width=5, height=2, font=("Arial", 14), command=lambda t=text: button_click(t)) btn.grid(row=row, column=col, padx=5, pady=5)
STEP 9: Run Main Event Loop: The root.Mainloop() function starts offevolved the GUI and maintains it running.
root.mainloop()
OUTPUT
A GUI calculator window appears with number and operator buttons. Users can click buttons to input numbers, perform calculations, and see results displayed in the entry field.