math)import tkinter as tk
import math
# Main window
root = tk.Tk()
root.title("Scientific Calculator")
root.geometry("430x550")
root.resizable(False, False)
# Display screen
equation = ""
input_text = tk.StringVar()
display = tk.Entry(root, font=("Arial", 20), textvariable=input_text, bd=10, justify="right")
display.grid(row=0, column=0, columnspan=5, padx=10, pady=20, ipadx=10, ipady=10)
# Button click function
def button_click(value):
global equation
equation += str(value)
input_text.set(equation)
# Clear screen
def clear():
global equation
equation = ""
input_text.set("")
# Evaluate the expression
def calculate():
global equation
try:
result = str(eval(equation))
input_text.set(result)
equation = result
except:
input_text.set("Error")
equation = ""
# Scientific Functions
def scientific_function(func):
global equation
try:
if func == "sqrt":
equation = str(math.sqrt(float(equation)))
elif func == "sin":
equation = str(math.sin(math.radians(float(equation))))
elif func == "cos":
equation = str(math.cos(math.radians(float(equation))))
elif func == "tan":
equation = str(math.tan(math.radians(float(equation))))
elif func == "log":
equation = str(math.log10(float(equation)))
elif func == "ln":
equation = str(math.log(float(equation)))
elif func == "fact":
equation = str(math.factorial(int(equation)))
input_text.set(equation)
except:
input_text.set("Error")
equation = ""
# Buttons layout
buttons = [
("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3), ("C", 1, 4),
("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3), ("(", 2, 4),
("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3), (")", 3, 4),
("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3), ("% ", 4, 4),
]
# Create normal buttons
for (text, row, col) in buttons:
if text == "=":
tk.Button(root, text=text, width=7, height=3, font=("Arial", 12),
command=calculate).grid(row=row, column=col)
elif text == "C":
tk.Button(root, text=text, width=7, height=3, font=("Arial", 12),
command=clear).grid(row=row, column=col)
else:
tk.Button(root, text=text, width=7, height=3, font=("Arial", 12),
command=lambda t=text: button_click(t)).grid(row=row, column=col)
# Scientific Buttons
scientific_buttons = [
("sin", "sin"), ("cos", "cos"), ("tan", "tan"),
("log", "log"), ("ln", "ln"), ("√", "sqrt"),
("x²", "square"), ("xⁿ", "power"), ("!", "fact"),
]
# Display scientific buttons
row = 5
col = 0
for (text, func) in scientific_buttons:
if func == "square":
cmd = lambda: button_click("**2")
elif func == "power":
cmd = lambda: button_click("**")
else:
cmd = lambda f=func: scientific_function(f)
tk.Button(root, text=text, width=7, height=3, font=("Arial", 12),
command=cmd).grid(row=row, column=col)
col += 1
if col > 4:
col = 0
row += 1
root.mainloop()
Please log in to like or comment.
good
nice
good for me