-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask 2 calculator
More file actions
94 lines (82 loc) · 2.97 KB
/
task 2 calculator
File metadata and controls
94 lines (82 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import tkinter as tk
from tkinter import messagebox
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Calculator")
self.root.resizable(False, False)
self.expression = ""
self.display = tk.Entry(
root,
font=("Arial", 20),
bd=10,
relief=tk.RIDGE,
justify="right"
)
self.display.grid(row=0, column=0, columnspan=4, pady=10, padx=10, ipady=5)
self.create_buttons()
self.root.bind("<Key>", self.key_handler)
def create_buttons(self):
buttons = [
("C", 1, 0), ("⌫", 1, 1), ("%", 1, 2), ("/", 1, 3),
("7", 2, 0), ("8", 2, 1), ("9", 2, 2), ("*", 2, 3),
("4", 3, 0), ("5", 3, 1), ("6", 3, 2), ("-", 3, 3),
("1", 4, 0), ("2", 4, 1), ("3", 4, 2), ("+", 4, 3),
("0", 5, 0), (".", 5, 1), ("=", 5, 2),
]
for (text, row, col) in buttons:
if text == "=":
btn = tk.Button(
self.root, text=text,
width=10, height=2,
font=("Arial", 14),
command=self.calculate
)
btn.grid(row=row, column=col, columnspan=2, padx=5, pady=5, sticky="nsew")
else:
btn = tk.Button(
self.root, text=text,
width=5, height=2,
font=("Arial", 14),
command=lambda t=text: self.on_button_click(t)
)
btn.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
def on_button_click(self, char):
if char == "C":
self.expression = ""
elif char == "⌫":
self.expression = self.expression[:-1]
else:
self.expression += str(char)
self.update_display()
def update_display(self):
self.display.delete(0, tk.END)
self.display.insert(tk.END, self.expression)
def calculate(self):
try:
expr = self.expression.replace("×", "*").replace("÷", "/")
result = str(eval(expr))
self.expression = result
self.update_display()
except ZeroDivisionError:
messagebox.showerror("Error", "Cannot divide by zero")
except Exception:
messagebox.showerror("Error", "Invalid Expression")
def key_handler(self, event):
key = event.keysym
if key in ("Return", "KP_Enter"):
self.calculate()
elif key == "BackSpace":
self.expression = self.expression[:-1]
self.update_display()
elif key == "Escape":
self.expression = ""
self.update_display()
else:
if event.char in "0123456789+-*/.%":
self.expression += event.char
self.update_display()
if __name__ == "__main__":
root = tk.Tk()
calc = Calculator(root)
root.mainloop()