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()
        display = ttk.Entry(root, textvariable=self.var_text, font=("Arial", 24), justify="right")
        display.grid(row=0, column=0, columnspan=4, padx=10, pady=20, sticky="nsew")

        # 按钮布局
        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 = ttk.Button(root, text=text, command=self.calc_result)
                btn.grid(row=row, column=col, rowspan=2, padx=5, pady=5, sticky="nsew")
            elif text == "C":
                btn = ttk.Button(root, text=text, command=self.clear_all)
                btn.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
            elif text == "←":
                btn = ttk.Button(root, text=text, command=self.backspace)
                btn.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
            else:
                btn = ttk.Button(root, text=text, command=lambda t=text: self.append_text(t))
                btn.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")

        # 0按钮占两格
        ttk.Button(root, text="0", command=lambda: self.append_text("0")).grid(row=5, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")

        # 网格权重自适应
        for i in range(6):
            root.grid_rowconfigure(i, weight=1)
        for i in range(4):
            root.grid_columnconfigure(i, weight=1)

    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()
            result = eval(expr)
            self.var_text.set(str(result))
        except ZeroDivisionError:
            self.var_text.set("除零错误")
        except Exception:
            self.var_text.set("输入错误")


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