import tkinter as tk
from tkinter import font
import math

class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("Python 计算器")
        self.root.geometry("400x600")
        self.root.resizable(False, False)
        
        # 设置颜色主题
        self.bg_color = "#2E2E2E"
        self.btn_color = "#4A4A4A"
        self.text_color = "#FFFFFF"
        self.accent_color = "#FF9500"
        
        self.root.configure(bg=self.bg_color)
        
        # 创建字体
        self.display_font = font.Font(family="Arial", size=28, weight="bold")
        self.button_font = font.Font(family="Arial", size=18, weight="normal")
        
        # 初始化变量
        self.current_input = ""
        self.previous_input = ""
        self.operation = None
        self.result_displayed = False
        
        # 创建界面
        self.create_widgets()
        
    def create_widgets(self):
        # 显示区域
        self.display_frame = tk.Frame(self.root, bg=self.bg_color, height=150)
        self.display_frame.pack(fill=tk.BOTH, padx=20, pady=(20, 10))
        
        # 历史显示
        self.history_label = tk.Label(
            self.display_frame, 
            text="", 
            bg=self.bg_color, 
            fg="#888888",
            font=("Arial", 12),
            anchor=tk.E
        )
        self.history_label.pack(fill=tk.BOTH, expand=True)
        
        # 当前输入显示
        self.display = tk.Entry(
            self.display_frame,
            font=self.display_font,
            bg=self.bg_color,
            fg=self.text_color,
            bd=0,
            justify=tk.RIGHT,
            insertbackground=self.text_color
        )
        self.display.pack(fill=tk.BOTH, expand=True)
        self.display.insert(0, "0")
        self.display.config(state='readonly')
        
        # 按钮区域
        self.buttons_frame = tk.Frame(self.root, bg=self.bg_color)
        self.buttons_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 按钮布局
        buttons = [
            ("C", 1, 0, 1, "#FF3B30"), ("±", 1, 1, 1, "#5C5C5C"), ("%", 1, 2, 1, "#5C5C5C"), ("÷", 1, 3, 1, self.accent_color),
            ("7", 2, 0, 1, self.btn_color), ("8", 2, 1, 1, self.btn_color), ("9", 2, 2, 1, self.btn_color), ("×", 2, 3, 1, self.accent_color),
            ("4", 3, 0, 1, self.btn_color), ("5", 3, 1, 1, self.btn_color), ("6", 3, 2, 1, self.btn_color), ("-", 3, 3, 1, self.accent_color),
            ("1", 4, 0, 1, self.btn_color), ("2", 4, 1, 1, self.btn_color), ("3", 4, 2, 1, self.btn_color), ("+", 4, 3, 1, self.accent_color),
            ("0", 5, 0, 2, self.btn_color), (".", 5, 2, 1, self.btn_color), ("=", 5, 3, 1, self.accent_color)
        ]
        
        # 科学计算按钮
        sci_buttons = [
            ("√", 0, 0, 1, "#5C5C5C"), ("x²", 0, 1, 1, "#5C5C5C"), ("1/x", 0, 2, 1, "#5C5C5C"), ("⌫", 0, 3, 1, "#5C5C5C"),
            ("sin", 0, 4, 1, "#5C5C5C"), ("cos", 1, 4, 1, "#5C5C5C"), ("tan", 2, 4, 1, "#5C5C5C"), ("π", 3, 4, 1, "#5C5C5C"),
            ("log", 4, 4, 1, "#5C5C5C"), ("ln", 5, 4, 1, "#5C5C5C")
        ]
        
        # 创建科学计算按钮
        for (text, row, col, colspan, color) in sci_buttons:
            btn = tk.Button(
                self.buttons_frame,
                text=text,
                font=self.button_font,
                bg=color,
                fg=self.text_color,
                activebackground=self.bg_color,
                activeforeground=self.text_color,
                bd=0,
                highlightthickness=0,
                command=lambda t=text: self.on_sci_button_click(t)
            )
            btn.grid(row=row, column=col, columnspan=colspan, sticky="nsew", padx=3, pady=3)
            btn.config(height=1)
        
        # 创建基本计算按钮
        for (text, row, col, colspan, color) in buttons:
            btn = tk.Button(
                self.buttons_frame,
                text=text,
                font=self.button_font,
                bg=color,
                fg=self.text_color,
                activebackground=self.bg_color,
                activeforeground=self.text_color,
                bd=0,
                highlightthickness=0,
                command=lambda t=text: self.on_button_click(t)
            )
            btn.grid(row=row, column=col, columnspan=colspan, sticky="nsew", padx=3, pady=3)
        
        # 配置网格权重
        for i in range(6):
            self.buttons_frame.grid_rowconfigure(i, weight=1)
        for i in range(5):
            self.buttons_frame.grid_columnconfigure(i, weight=1)
    
    def on_button_click(self, value):
        if value == "C":
            self.clear_all()
        elif value == "⌫":
            self.backspace()
        elif value == "=":
            self.calculate()
        elif value in ["+", "-", "×", "÷"]:
            self.set_operation(value)
        elif value == "±":
            self.toggle_sign()
        elif value == "%":
            self.percentage()
        else:
            self.add_to_input(value)
    
    def on_sci_button_click(self, value):
        try:
            current = float(self.current_input) if self.current_input else 0
            
            if value == "√":
                if current >= 0:
                    result = math.sqrt(current)
                    self.display_result(f"√({current})", result)
                else:
                    self.show_error("负数不能开平方根")
            elif value == "x²":
                result = current ** 2
                self.display_result(f"({current})²", result)
            elif value == "1/x":
                if current != 0:
                    result = 1 / current
                    self.display_result(f"1/({current})", result)
                else:
                    self.show_error("除数不能为零")
            elif value == "sin":
                result = math.sin(math.radians(current))
                self.display_result(f"sin({current}°)", result)
            elif value == "cos":
                result = math.cos(math.radians(current))
                self.display_result(f"cos({current}°)", result)
            elif value == "tan":
                if current % 90 == 0 and (current / 90) % 2 != 0:
                    self.show_error("正切值不存在")
                else:
                    result = math.tan(math.radians(current))
                    self.display_result(f"tan({current}°)", result)
            elif value == "π":
                self.current_input = str(math.pi)
                self.update_display()
            elif value == "log":
                if current > 0:
                    result = math.log10(current)
                    self.display_result(f"log({current})", result)
                else:
                    self.show_error("对数参数必须大于0")
            elif value == "ln":
                if current > 0:
                    result = math.log(current)
                    self.display_result(f"ln({current})", result)
                else:
                    self.show_error("自然对数参数必须大于0")
        except Exception as e:
            self.show_error("计算错误")
    
    def add_to_input(self, value):
        if self.result_displayed:
            self.current_input = ""
            self.result_displayed = False
        
        if value == ".":
            if "." not in self.current_input:
                if not self.current_input:
                    self.current_input = "0"
                self.current_input += value
        else:
            if self.current_input == "0":
                self.current_input = value
            else:
                self.current_input += value
        
        self.update_display()
    
    def set_operation(self, op):
        if self.current_input:
            if self.previous_input and self.operation and not self.result_displayed:
                self.calculate()
            
            self.previous_input = self.current_input
            self.operation = op
            self.current_input = ""
            self.history_label.config(text=f"{self.previous_input} {self.get_operation_symbol(op)}")
    
    def calculate(self):
        if not self.previous_input or not self.current_input or not self.operation:
            return
        
        try:
            num1 = float(self.previous_input)
            num2 = float(self.current_input)
            result = 0
            
            if self.operation == "+":
                result = num1 + num2
            elif self.operation == "-":
                result = num1 - num2
            elif self.operation == "×":
                result = num1 * num2
            elif self.operation == "÷":
                if num2 == 0:
                    self.show_error("除数不能为零")
                    return
                result = num1 / num2
            
            # 格式化结果
            if result.is_integer():
                result_str = str(int(result))
            else:
                result_str = f"{result:.10f}".rstrip('0').rstrip('.')
            
            history_text = f"{self.previous_input} {self.get_operation_symbol(self.operation)} {self.current_input} ="
            self.history_label.config(text=history_text)
            
            self.current_input = result_str
            self.update_display()
            self.result_displayed = True
            self.previous_input = ""
            self.operation = None
            
        except Exception as e:
            self.show_error("计算错误")
    
    def display_result(self, operation_text, result):
        """显示科学计算结果"""
        if result.is_integer():
            result_str = str(int(result))
        else:
            result_str = f"{result:.10f}".rstrip('0').rstrip('.')
        
        self.history_label.config(text=f"{operation_text} =")
        self.current_input = result_str
        self.update_display()
        self.result_displayed = True
    
    def clear_all(self):
        self.current_input = ""
        self.previous_input = ""
        self.operation = None
        self.result_displayed = False
        self.history_label.config(text="")
        self.display.config(state='normal')
        self.display.delete(0, tk.END)
        self.display.insert(0, "0")
        self.display.config(state='readonly')
    
    def backspace(self):
        if self.current_input:
            self.current_input = self.current_input[:-1]
            if not self.current_input:
                self.current_input = "0"
            self.update_display()
    
    def toggle_sign(self):
        if self.current_input and self.current_input != "0":
            if self.current_input[0] == "-":
                self.current_input = self.current_input[1:]
            else:
                self.current_input = "-" + self.current_input
            self.update_display()
    
    def percentage(self):
        if self.current_input:
            try:
                value = float(self.current_input) / 100
                if value.is_integer():
                    self.current_input = str(int(value))
                else:
                    self.current_input = str(value)
                self.update_display()
            except:
                self.show_error("错误")
    
    def update_display(self):
        self.display.config(state='normal')
        self.display.delete(0, tk.END)
        
        # 限制显示长度
        display_text = self.current_input if self.current_input else "0"
        if len(display_text) > 15:
            display_text = display_text[:15]
        
        self.display.insert(0, display_text)
        self.display.config(state='readonly')
    
    def get_operation_symbol(self, op):
        symbols = {
            "+": "+",
            "-": "−",
            "×": "×",
            "÷": "÷"
        }
        return symbols.get(op, op)
    
    def show_error(self, message):
        self.history_label.config(text=message, fg="#FF3B30")
        self.current_input = "0"
        self.update_display()
        self.result_displayed = True

def main():
    root = tk.Tk()
    app = Calculator(root)
    root.mainloop()

if __name__ == "__main__":
    main()