-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator_3.py
More file actions
79 lines (71 loc) · 2.86 KB
/
calculator_3.py
File metadata and controls
79 lines (71 loc) · 2.86 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
import tkinter as tk
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Calculator")
# Create input field
self.entry = tk.Entry(self.root, width=30, font=("Arial", 16))
self.entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# Create buttons
self.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), ".": (4, 1), "=": (4, 2), "+": (4, 3),
"AC": (5, 0), "C": (5, 1), "M+": (5, 2), "M-": (5, 3),
"MR": (6, 0), "MC": (6, 1), "MS": (6, 2), "%": (6, 3),
"sin": (7, 0), "cos": (7, 1), "tan": (7, 2), "log": (7, 3),
"ln": (8, 0), "sqrt": (8, 1), "x^2": (8, 2), "x^y": (8, 3),
}
for key, (row, col) in self.buttons.items():
button = tk.Button(self.root, text=key, font=("Arial", 14), command=lambda key=key: self.handle_button(key))
button.grid(row=row, column=col, padx=5, pady=5)
# Bind keyboard events
self.root.bind("<Key>", self.handle_key)
def handle_button(self, key):
if key in self.buttons:
if key == "=":
try:
result = eval(self.entry.get())
self.entry.delete(0, tk.END)
self.entry.insert(0, str(result))
except Exception as e:
self.entry.delete(0, tk.END)
self.entry.insert(0, "Error")
elif key == "AC":
self.entry.delete(0, tk.END)
elif key == "C":
self.entry.delete(len(self.entry.get()) - 1, tk.END)
elif key == "M+":
try:
self.memory += float(self.entry.get())
except ValueError:
pass
elif key == "M-":
try:
self.memory -= float(self.entry.get())
except ValueError:
pass
elif key == "MR":
self.entry.delete(0, tk.END)
self.entry.insert(0, str(self.memory))
elif key == "MC":
self.memory = 0
elif key == "%":
try:
value = float(self.entry.get())
result = value / 100
self.entry.delete(0, tk.END)
self.entry.insert(0, str(result))
except ValueError:
pass
else:
self.entry.insert(tk.END, key)
def handle_key(self, event):
key = event.char
if key in self.buttons:
self.handle_button(key)
if __name__ == "__main__":
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()