-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
49 lines (37 loc) · 1.4 KB
/
Copy pathcalculator.py
File metadata and controls
49 lines (37 loc) · 1.4 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
import tkinter as tk
from tkinter import messagebox
from tkinter.constants import SUNKEN
window = tk.Tk()
window.title("Calculator")
frame = tk.Frame(master=window, bg="gray", padx=10, pady=10)
frame.pack()
entry = tk.Entry(master=frame, relief=SUNKEN, width=30)
entry.grid(row=0, column=0, columnspan=4, pady=2, padx=2)
def btn_click(number):
entry.insert(tk.END, number)
def equal():
try:
y = str(eval(entry.get()))
entry.delete(0, tk.END)
entry.insert(0, y)
except:
messagebox.showerror("Error", "Syntax Error")
def clear():
entry.delete(0, tk.END)
# Create number buttons
for i in range(1, 10):
btn = tk.Button(master=frame, text=str(i), command=lambda i=i: btn_click(i))
btn.grid(row=(i-1)//3+1, column=(i-1)%3, pady=2, padx=2)
# Other buttons
btn_0 = tk.Button(master=frame, text="0", command=lambda: btn_click(0))
btn_0.grid(row=4, column=1, pady=2, padx=2)
btn_clear = tk.Button(master=frame, text="C", command=clear)
btn_clear.grid(row=4, column=0, pady=2, padx=2)
btn_equal = tk.Button(master=frame, text="=", command=equal)
btn_equal.grid(row=4, column=2, pady=2, padx=2)
# Operator buttons
operators = ['+', '-', '*', '/']
for i, op in enumerate(operators):
btn = tk.Button(master=frame, text=op, command=lambda op=op: btn_click(op))
btn.grid(row=i+1, column=3, pady=2, padx=2)
window.mainloop()