import tkinter as tk
from tkinter import messagebox
import math
class Calculator(tk.Tk):
def __init__(self):
super().__init__()
self.title("Calculadora Avançada")
self.geometry("400x600")
self.resizable(False, False)
self.configure(bg="#222222")
self.expression = ""
self.history = []
self.is_radians = False # controla modo graus/radianos
self.create_widgets()
def create_widgets(self):
# Display do resultado
self.display = tk.Entry(self, font=("Arial", 24), bg="#333333", fg="#ffffff", borderwidth=0, relief=tk.FLAT, justify="right")
self.display.pack(fill="x", ipady=15, padx=10, pady=10)
# Label para o history
self.history_label = tk.Label(self, text="Histórico:", bg="#222222", fg="#aaa", anchor="w")
self.history_label.pack(fill="x", padx=10)
# Text widget para mostrar history
self.history_text = tk.Text(self, height=6, bg="#111111", fg="#0f0", font=("Courier", 10), borderwidth=0)
self.history_text.pack(fill="x", padx=10)
self.history_text.configure(state="disabled")
# Frame para botoes
btns_frame = tk.Frame(self, bg="#222222")
btns_frame.pack(expand=True, fill="both", padx=10, pady=10)
# Linhas de botoes: usando grid
buttons = [
["C", "⌫", "(", ")", "π"],
["sin", "cos", "tan", "ln", "log"],
["7", "8", "9", "/", "√"],
["4", "5", "6", "*", "^"],
["1", "2", "3", "-", "%"],
["±", "0", ".", "rad", "+"],
["Modo Grau/Rad", "=", "", "", ""]
]
for r, row in enumerate(buttons):
for c, btn_text in enumerate(row):
if not btn_text:
continue # pular espaços vazios
btn = tk.Button(btns_frame, text=btn_text, font=("Arial", 14),
fg="#fff", bg="#444444",
activebackground="#666666",
borderwidth=0,
command=lambda x=btn_text: self.on_button_click(x))
btn.grid(row=r, column=c, sticky="nsew", padx=5, pady=5)
# Configurar pesos para resize igual dos btns
for i in range(len(buttons)):
btns_frame.rowconfigure(i, weight=1)
for j in range(5):
btns_frame.columnconfigure(j, weight=1)
def on_button_click(self, char):
if char == "C":
self.expression = ""
self.update_display()
elif char == "⌫":
self.expression = self.expression[:-1]
self.update_display()
elif char == "=":
self.calculate()
elif char == "±":
self.toggle_sign()
elif char == "π":
self.expression += str(math.pi)
self.update_display()
elif char == "√":
self.expression += "√("
self.update_display()
elif char == "^":
self.expression += "**"
self.update_display()
elif char in ("sin", "cos", "tan", "ln", "log"):
self.expression += char + "("
self.update_display()
elif char == "rad":
self.is_radians = not self.is_radians
mode = "rad" if self.is_radians else "grau"
messagebox.showinfo("Modo trigonométrico", f"Modo alterado para: {mode}")
elif char == "Modo Grau/Rad":
self.is_radians = not self.is_radians
mode = "Radianos" if self.is_radians else "Graus"
messagebox.showinfo("Modo trigonométrico", f"Modo alterado para: {mode}")
elif char == "%":
self.expression += "/100"
self.update_display()
else:
self.expression += char
self.update_display()
def toggle_sign(self):
# Tenta alternar o sinal do número mais à direita
import re
pattern = r'(-?\d+\.?\d*)$'
match = re.search(pattern, self.expression)
if match:
val = match.group()
start = match.start()
# Remove valor atual da expressão
self.expression = self.expression[:start]
# Toggle sinal
if val.startswith("-"):
val = val[1:]
else:
val = "-" + val
self.expression += val
else:
if self.expression == "":
self.expression = "-"
else:
self.expression += "-"
self.update_display()
def update_display(self):
# Atualiza o entry com a expressão atual
self.display.delete(0, tk.END)
self.display.insert(0, self.expression)
def calculate(self):
exp = self.expression
# Substituições para funções especiais
try:
# Substitui √( por math.sqrt(
exp = exp.replace("√(", "math.sqrt(")
# Funções trigonométricas: substituir pelas funções que respeitam graus/radianos
def trig_repl(match):
func = match.group(1)
val = match.group(2)
if self.is_radians:
return f"math.{func}({val})"
else:
# converter graus para rad
return f"math.{func}(math.radians({val}))"
import re
exp = re.sub(r'(sin|cos|tan)\(([^()]*)\)', trig_repl, exp)
# Funções log e ln
exp = exp.replace("ln(", "math.log(") # logaritmo natural
exp = exp.replace("log(", "math.log10(")
# Evaluate expression de forma segura:
allowed_names = {
"math": math,
"__builtins__": {},
"abs": abs,
"round": round,
"pow": pow,
}
result = eval(exp, allowed_names)
if isinstance(result, float) and result.is_integer():
result = int(result)
self.history.append(f"{self.expression} = {result}")
self.update_history()
self.expression = str(result)
self.update_display()
except Exception as e:
messagebox.showerror("Erro", f"Expressão inválida!\n{e}")
def update_history(self):
self.history_text.configure(state="normal")
self.history_text.delete(1.0, tk.END)
last = "\n".join(self.history[-6:])
self.history_text.insert(tk.END, last)
self.history_text.configure(state="disabled")
if __name__ == "__main__":
app = Calculator()
app.mainloop()