|
| 1 | +# Import the tkinter library for creating GUI applications |
| 2 | +import tkinter as tk |
| 3 | + |
| 4 | +# Create the main application window |
| 5 | +root = tk.Tk() |
| 6 | +root.title("Calculator") # Set the window title |
| 7 | +root.geometry("300x400") # Set window size (width x height) |
| 8 | + |
| 9 | +# Create an Entry widget to display numbers and results |
| 10 | +entry = tk.Entry( |
| 11 | + root, |
| 12 | + font=("Arial", 20), # Font style and size |
| 13 | + borderwidth=5, # Thickness of border |
| 14 | + relief="ridge", # Border style |
| 15 | + justify="right" # Align text to the right |
| 16 | +) |
| 17 | +entry.pack(fill="both", padx=10, pady=10) |
| 18 | + |
| 19 | +# Function to insert numbers/operators when a button is clicked |
| 20 | +def click(value): |
| 21 | + entry.insert(tk.END, value) # Insert value at the end of the entry box |
| 22 | + |
| 23 | +# Function to clear the display |
| 24 | +def clear(): |
| 25 | + entry.delete(0, tk.END) # Delete everything from entry box |
| 26 | + |
| 27 | +# Function to evaluate the expression |
| 28 | +def calculate(): |
| 29 | + try: |
| 30 | + # Evaluate the mathematical expression entered by the user |
| 31 | + result = eval(entry.get()) |
| 32 | + entry.delete(0, tk.END) # Clear entry box |
| 33 | + entry.insert(tk.END, result) # Display result |
| 34 | + except: |
| 35 | + # If any error occurs (invalid expression) |
| 36 | + entry.delete(0, tk.END) |
| 37 | + entry.insert(tk.END, "Error") |
| 38 | + |
| 39 | +# List of calculator buttons in order |
| 40 | +buttons = [ |
| 41 | + '7', '8', '9', '/', |
| 42 | + '4', '5', '6', '*', |
| 43 | + '1', '2', '3', '-', |
| 44 | + '0', '.', '=', '+' |
| 45 | +] |
| 46 | + |
| 47 | +# Create a frame to hold all the buttons |
| 48 | +frame = tk.Frame(root) |
| 49 | +frame.pack() |
| 50 | + |
| 51 | +row = 0 |
| 52 | +col = 0 |
| 53 | + |
| 54 | +# Create buttons dynamically using a loop |
| 55 | +for btn in buttons: |
| 56 | + if btn == "=": |
| 57 | + # '=' button performs calculation |
| 58 | + tk.Button( |
| 59 | + frame, |
| 60 | + text=btn, |
| 61 | + width=5, |
| 62 | + height=2, |
| 63 | + command=calculate |
| 64 | + ).grid(row=row, column=col) |
| 65 | + else: |
| 66 | + # Other buttons insert numbers/operators |
| 67 | + tk.Button( |
| 68 | + frame, |
| 69 | + text=btn, |
| 70 | + width=5, |
| 71 | + height=2, |
| 72 | + command=lambda b=btn: click(b) |
| 73 | + ).grid(row=row, column=col) |
| 74 | + |
| 75 | + col += 1 |
| 76 | + if col > 3: # Move to next row after 4 buttons |
| 77 | + col = 0 |
| 78 | + row += 1 |
| 79 | + |
| 80 | +# Clear button placed below the calculator buttons |
| 81 | +tk.Button( |
| 82 | + root, |
| 83 | + text="Clear", |
| 84 | + width=20, |
| 85 | + height=2, |
| 86 | + command=clear |
| 87 | +).pack(pady=10) |
| 88 | + |
| 89 | +# Start the GUI event loop |
| 90 | +root.mainloop() |
0 commit comments