import tkinter as tk
from tkinter import ttk, messagebox
import math

def calculate():
    try:
        num = float(entry.get())
        formula = box.get()

        if formula == "平方根 sqrt":
            if num < 0:
                raise ValueError("负数不能开平方")
            result = math.sqrt(num)

        elif formula == "正弦 sin":
            result = math.sin(math.radians(num))

        elif formula == "余弦 cos":
            result = math.cos(math.radians(num))

        elif formula == "正切 tan":
            result = math.tan(math.radians(num))

        elif formula == "自然对数 ln":
            if num <= 0:
                raise ValueError("对数定义域必须大于0")
            result = math.log(num)

        else:
            result = "未选择公式"

        result_label.config(text=f"结果：{result:.4f}")

    except ValueError as e:
        messagebox.showerror("输入错误", str(e))
    except Exception as e:
        messagebox.showerror("计算错误", str(e))

# ===== 创建窗口 =====
root = tk.Tk()
root.title("004. 数学公式查询")
root.geometry("380x260")
root.resizable(False, False)

# ===== 控件 =====
tk.Label(root, text="数学公式查询系统",
         font=("微软雅黑", 14, "bold")).pack(pady=10)

frame = tk.Frame(root)
frame.pack(pady=5)

tk.Label(frame, text="输入数值：").pack(side=tk.LEFT)
entry = tk.Entry(frame, width=12)
entry.pack(side=tk.LEFT)

# ✅ 关键修正：显式使用 ttk.Style
style = ttk.Style()
box = ttk.Combobox(root, width=18, state="readonly")
box['values'] = [
    "平方根 sqrt",
    "正弦 sin",
    "余弦 cos",
    "正切 tan",
    "自然对数 ln"
]
box.current(0)
box.pack(pady=8)

tk.Button(
    root, text="开始计算",
    width=15,
    bg="#4CAF50", fg="white",
    command=calculate
).pack(pady=8)

result_label = tk.Label(root, text="结果：", font=("宋体", 12))
result_label.pack(pady=10)

# ===== 运行 =====
root.mainloop()