import tkinter as tk
from tkinter import ttk

class Calculator:
    def __init__(self, root):
        # 主窗口设置
        self.root = root
        self.root.title("红色计算器")
        self.root.geometry("480x600")
        self.root.resizable(False, False)
        self.root.configure(bg="#FFE7E7")

        self.expression = ""
        self.display_text = tk.StringVar(value="0")

        # 显示屏优化
        display = tk.Entry(
            root,
            textvariable=self.display_text,
            font=("Arial", 34),
            justify="right",
            state="readonly",
            readonlybackground="#fefefe"
        )
        display.pack(pady=20, padx=18, fill="x", ipady=18)

        # 按钮框架
        btn_frame = tk.Frame(root, bg="#FFDDDD")
        btn_frame.pack(pady=10, padx=15)

        # 修正布局：第五行第四列留空，不再重复加号
        buttons = [
            ["C", "←", "+/-", "/"],
            ["7", "8", "9", "*"],
            ["4", "5", "6", "-"],
            ["1", "2", "3", "+"],
            ["0", ".", "=", ""]
        ]

        # 配色（键名全部正确，无拼写错误）
        func_btn = {"bg": "#D92121", "fg": "white", "activebackground": "#B01515"}
        op_btn = {"bg": "#ED5555", "fg": "white", "activebackground": "#C93E3E"}
        num_btn = {"bg": "#FFC8C8", "fg": "#000000", "activebackground": "#FFAAAA"}
        equal_btn = {"bg": "#800000", "fg": "white", "activebackground": "#590000"}

        # 生成按钮
        for row_idx, row_data in enumerate(buttons):
            for col_idx, word in enumerate(row_data):
                # 空字符直接跳过，不生成按钮
                if word == "":
                    continue
                if word in ["C", "←", "+/-"]:
                    color = func_btn
                elif word in ["+", "-", "*", "/"]:
                    color = op_btn
                elif word == "=":
                    color = equal_btn
                else:
                    color = num_btn

                btn = tk.Button(
                    btn_frame,
                    text=word,
                    font=("Arial", 20),
                    width=6,
                    height=2,
                    bg=color["bg"],
                    fg=color["fg"],
                    activebackground=color["activebackground"],
                    bd=2,
                    relief="raised",
                    command=lambda t=word: self.click_btn(t)
                )
                btn.grid(row=row_idx, column=col_idx, padx=4, pady=4)

    def click_btn(self, text):
        if text == "C":
            self.expression = ""
            self.display_text.set("0")

        elif text == "←":
            self.expression = self.expression[:-1]
            self.display_text.set(self.expression if self.expression else "0")

        elif text == "+/-":
            if not self.expression:
                self.expression = "-"
            elif self.expression.startswith("-"):
                self.expression = self.expression[1:]
            else:
                self.expression = "-" + self.expression
            self.display_text.set(self.expression)

        elif text == "=":
            try:
                result = eval(self.expression)
                if isinstance(result, float) and result.is_integer():
                    result = int(result)
                self.display_text.set(str(result))
                self.expression = str(result)
            except ZeroDivisionError:
                self.display_text.set("除数不能为0")
                self.expression = ""
            except Exception:
                self.display_text.set("表达式错误")
                self.expression = ""
        else:
            self.expression += text
            self.display_text.set(self.expression)

if __name__ == "__main__":
    win = tk.Tk()
    Calculator(win)
    win.mainloop()