import tkinter as tk
import math
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(tk.END, current + str(number))
def button_clear():
entry.delete(0, tk.END)
def button_equal():
expression = entry.get()
try:
result = eval(expression)
entry.delete(0, tk.END)
entry.insert(tk.END, result)
except Exception as e:
entry.delete(0, tk.END)
entry.insert(tk.END, “Error”)
def button_sin():
value = float(entry.get())
result = math.sin(math.radians(value))
entry.delete(0, tk.END)
entry.insert(tk.END, result)
def button_cos():
value = float(entry.get())
result = math.cos(math.radians(value))
entry.delete(0, tk.END)
entry.insert(tk.END, result)
def button_tan():
value = float(entry.get())
result = math.tan(math.radians(value))
entry.delete(0, tk.END)
entry.insert(tk.END, result)
def button_log():
value = float(entry.get())
result = math.log10(value)
entry.delete(0, tk.END)
entry.insert(tk.END, result)
def button_factorial():
value = int(entry.get())
result = math.factorial(value)
entry.delete(0, tk.END)
entry.insert(tk.END, result)
root = tk.Tk()
root.title(“Calculator”)
entry = tk.Entry(root, width=30, font=(“Arial”, 18))
entry.grid(row=0, column=0, columnspan=5, padx=10, pady=10)
buttons = [
‘7’, ‘8’, ‘9’, ‘/’,
‘4’, ‘5’, ‘6’, ‘*’,
‘1’, ‘2’, ‘3’, ‘-‘,
‘0’, ‘.’, ‘=’, ‘+’,
‘C’, ‘sin’, ‘cos’, ‘tan’,
‘log’, ‘!’, ‘(‘, ‘)’
]
row = 1
col = 0
for button in buttons:
if button == ‘=’:
tk.Button(root, text=button, width=6, height=2, command=button_equal).grid(row=row, column=col)
elif button == ‘C’:
tk.Button(root, text=button, width=6, height=2, command=button_clear).grid(row=row, column=col)
elif button == ‘sin’:
tk.Button(root, text=button, width=6, height=2, command=button_sin).grid(row=row, column=col)
elif button == ‘cos’:
tk.Button(root, text=button, width=6, height=2, command=button_cos).grid(row=row, column=col)
elif button == ‘tan’:
tk.Button(root, text=button, width=6, height=2, command=button_tan).grid(row=row, column=col)
elif button == ‘log’:
tk.Button(root, text=button, width=6, height=2, command=button_log).grid(row=row, column=col)
elif button == ‘!’:
tk.Button(root, text=button, width=6, height=2, command=button_factorial).grid(row=row, column=col)
else:
tk.Button(root, text=button, width=6, height=2, command=lambda key=button: button_click(key)).grid(row=row, column=col)
col += 1
if col > 4:
col = 0
row += 1
root.mainloop()