import tkinter as tk
from tkinter import ttk

class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("简易计算器")
        self.root.geometry("320x420")
        self.root.resizable(False, False)

        # 显示文本框
        self.var_text = tk.StringVar()
        entry = ttk.Entry(
            root,
            textvariable=self.var_text,
            font=("Arial", 24),
            justify="right"
        )
        entry.pack(pady=15, padx=10, fill="x")

        # 按钮布局
        btn_frame = tk.Frame(root)
        btn_frame.pack()

        buttons = [
            ("C", 1, 0), ("←", 1, 1), ("/", 1, 2), ("*", 1, 3),
            ("7", 2, 0), ("8", 2, 1), ("9", 2, 2), ("-", 2, 3),
            ("4", 3, 0), ("5", 3, 1), ("6", 3, 2), ("+", 3, 3),
            ("1", 4, 0), ("2", 4, 1), ("3", 4, 2), ("=", 4, 3),
            ("0", 5, 0), (".", 5, 1)
        ]

        for text, row, col in buttons:
            if text == "=":
                btn = tk.Button(
                    btn_frame, text=text, width=4, height=2,
                    font=("Arial", 16), bg="#4285F4", fg="white",
                    command=self.calc_result
                )
            elif text == "C":
                btn = tk.Button(
                    btn_frame, text=text, width=4, height=2,
                    font=("Arial", 16), bg="#EA4335", fg="white",
                    command=self.clear_all
                )
            elif text == "←":
                btn = tk.Button(
                    btn_frame, text=text, width=4, height=2,
                    font=("Arial", 16), bg="#FBBC05",
                    command=self.backspace
                )
            else:
                btn = tk.Button(
                    btn_frame, text=text, width=4, height=2,
                    font=("Arial", 16),
                    command=lambda t=text: self.append_text(t)
                )
            btn.grid(row=row, column=col, padx=4, pady=4)

        # 0按钮占两格
        btn0 = tk.Button(
            btn_frame, text="0", width=10, height=2,
            font=("Arial", 16),
            command=lambda: self.append_text("0")
        )
        btn0.grid(row=5, column=0, columnspan=2, padx=4, pady=4)

    def append_text(self, char):
        """追加字符到输入框"""
        current = self.var_text.get()
        self.var_text.set(current + char)

    def clear_all(self):
        """清空"""
        self.var_text.set("")

    def backspace(self):
        """退格删除一位"""
        current = self.var_text.get()
        self.var_text.set(current[:-1])

    def calc_result(self):
        """计算结果"""
        try:
            expr = self.var_text.get()
            # 安全计算表达式
            res = eval(expr)
            # 去除多余小数 .0
            if isinstance(res, float) and res.is_integer():
                res = int(res)
            self.var_text.set(str(res))
        except ZeroDivisionError:
            self.var_text.set("除零错误")
        except Exception:
            self.var_text.set("表达式错误")

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