import tkinter as tk
from tkinter import font


class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("Python计算器")
        self.root.geometry("350x500")
        self.root.resizable(False, False)

        # 设置颜色主题
        self.bg_color = "#2b2b2b"
        self.btn_bg = "#3c3c3c"
        self.btn_fg = "#ffffff"
        self.display_bg = "#1e1e1e"
        self.display_fg = "#ffffff"
        self.operator_color = "#ff9500"
        self.special_color = "#a6a6a6"

        self.root.configure(bg=self.bg_color)

        # 创建字体
        self.display_font = font.Font(
            family="Segoe UI", size=24, weight="bold")
        self.button_font = font.Font(family="Segoe UI", size=18)

        # 计算器状态
        self.current_input = "0"
        self.previous_input = ""
        self.operator = ""
        self.waiting_for_new_input = False
        self.decimal_used = False

        # 创建界面
        self.create_widgets()

    def create_widgets(self):
        # 创建显示区域
        self.display_frame = tk.Frame(
            self.root, bg=self.display_bg, height=120)
        self.display_frame.pack(fill=tk.X, padx=10, pady=(10, 5))

        # 上部显示区域（历史记录）
        self.history_label = tk.Label(
            self.display_frame,
            text="",
            bg=self.display_bg,
            fg="#888888",
            font=("Segoe UI", 12),
            anchor="e"
        )
        self.history_label.pack(fill=tk.X, padx=10, pady=(10, 0))

        # 主显示区域
        self.display_label = tk.Label(
            self.display_frame,
            text="0",
            bg=self.display_bg,
            fg=self.display_fg,
            font=self.display_font,
            anchor="e"
        )
        self.display_label.pack(fill=tk.X, padx=10, pady=(5, 10))

        # 创建按钮区域
        self.button_frame = tk.Frame(self.root, bg=self.bg_color)
        self.button_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 按钮布局
        buttons = [
            ("C", 1, 0, self.special_color, self.clear_all),
            ("±", 1, 1, self.special_color, self.negate),
            ("%", 1, 2, self.special_color, self.percentage),
            ("÷", 1, 3, self.operator_color, lambda: self.set_operator("÷")),

            ("7", 2, 0, self.btn_bg, lambda: self.add_digit("7")),
            ("8", 2, 1, self.btn_bg, lambda: self.add_digit("8")),
            ("9", 2, 2, self.btn_bg, lambda: self.add_digit("9")),
            ("×", 2, 3, self.operator_color, lambda: self.set_operator("×")),

            ("4", 3, 0, self.btn_bg, lambda: self.add_digit("4")),
            ("5", 3, 1, self.btn_bg, lambda: self.add_digit("5")),
            ("6", 3, 2, self.btn_bg, lambda: self.add_digit("6")),
            ("-", 3, 3, self.operator_color, lambda: self.set_operator("-")),

            ("1", 4, 0, self.btn_bg, lambda: self.add_digit("1")),
            ("2", 4, 1, self.btn_bg, lambda: self.add_digit("2")),
            ("3", 4, 2, self.btn_bg, lambda: self.add_digit("3")),
            ("+", 4, 3, self.operator_color, lambda: self.set_operator("+")),

            ("0", 5, 0, self.btn_bg, lambda: self.add_digit("0")),
            (".", 5, 1, self.btn_bg, self.add_decimal),
            ("=", 5, 2, self.operator_color, self.calculate, 2)
        ]

        # 创建按钮
        for btn_text, row, col, color, command, *args in buttons:
            if btn_text == "0":
                btn = tk.Button(
                    self.button_frame,
                    text=btn_text,
                    bg=color,
                    fg=self.btn_fg,
                    font=self.button_font,
                    borderwidth=0,
                    command=command
                )
                btn.grid(row=row, column=col, columnspan=2,
                         sticky="nsew", padx=2, pady=2)
            elif btn_text == "=" and args:
                btn = tk.Button(
                    self.button_frame,
                    text=btn_text,
                    bg=color,
                    fg=self.btn_fg,
                    font=self.button_font,
                    borderwidth=0,
                    command=command
                )
                btn.grid(row=row, column=col,
                         columnspan=args[0], sticky="nsew", padx=2, pady=2)
            else:
                btn = tk.Button(
                    self.button_frame,
                    text=btn_text,
                    bg=color,
                    fg=self.btn_fg,
                    font=self.button_font,
                    borderwidth=0,
                    command=command
                )
                btn.grid(row=row, column=col, sticky="nsew", padx=2, pady=2)

        # 配置网格权重
        for i in range(4):
            self.button_frame.columnconfigure(i, weight=1)
        for i in range(1, 6):
            self.button_frame.rowconfigure(i, weight=1)

    def add_digit(self, digit):
        if self.waiting_for_new_input or self.current_input == "0":
            self.current_input = digit
            self.waiting_for_new_input = False
        else:
            self.current_input += digit

        self.update_display()

    def add_decimal(self):
        if not self.decimal_used:
            if self.waiting_for_new_input or self.current_input == "0":
                self.current_input = "0."
                self.waiting_for_new_input = False
            else:
                self.current_input += "."
            self.decimal_used = True
            self.update_display()

    def set_operator(self, op):
        if self.operator and not self.waiting_for_new_input:
            self.calculate()

        self.previous_input = self.current_input
        self.operator = op
        self.waiting_for_new_input = True
        self.decimal_used = False

        # 更新历史显示
        self.update_history()

    def calculate(self):
        if not self.operator or not self.previous_input:
            return

        try:
            num1 = float(self.previous_input)
            num2 = float(self.current_input)
            result = 0

            if self.operator == "+":
                result = num1 + num2
            elif self.operator == "-":
                result = num1 - num2
            elif self.operator == "×":
                result = num1 * num2
            elif self.operator == "÷":
                if num2 == 0:
                    self.current_input = "错误"
                    self.update_display()
                    return
                result = num1 / num2

            # 格式化结果
            if result.is_integer():
                self.current_input = str(int(result))
            else:
                # 限制小数位数
                self.current_input = f"{result:.10f}".rstrip('0').rstrip('.')
                if len(self.current_input) > 12:
                    self.current_input = f"{result:.6e}"

            # 更新历史显示
            self.history_label.config(
                text=f"{self.previous_input} {self.operator} {num2} =")

            self.operator = ""
            self.waiting_for_new_input = True
            self.decimal_used = "." in self.current_input

            self.update_display()

        except Exception as e:
            self.current_input = "错误"
            self.update_display()

    def clear_all(self):
        self.current_input = "0"
        self.previous_input = ""
        self.operator = ""
        self.waiting_for_new_input = False
        self.decimal_used = False

        self.history_label.config(text="")
        self.update_display()

    def clear_entry(self):
        self.current_input = "0"
        self.decimal_used = False
        self.update_display()

    def negate(self):
        if self.current_input != "0" and self.current_input != "错误":
            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):
        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.current_input = "错误"
            self.update_display()

    def update_display(self):
        # 限制显示长度
        display_text = self.current_input
        if len(display_text) > 12:
            # 尝试用科学计数法显示
            try:
                value = float(display_text)
                display_text = f"{value:.6e}"
            except:
                if len(display_text) > 12:
                    display_text = display_text[:12] + "..."

        self.display_label.config(text=display_text)

    def update_history(self):
        if self.operator and self.previous_input:
            self.history_label.config(
                text=f"{self.previous_input} {self.operator}")
        else:
            self.history_label.config(text="")


def main():
    root = tk.Tk()
    calculator = Calculator(root)
    root.mainloop()


if __name__ == "__main__":
    main()
