import tkinter as tk
from tkinter import messagebox

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 = tk.Entry(
            root,
            textvariable=self.var_text,
            font=("Arial", 24),
            justify="right",
            bd=10
        )
        entry.pack(fill=tk.BOTH, padx=10, pady=10)

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

        # 按钮文字排布
        buttons = [
            ["C", "←", "/", "*"],
            ["7", "8", "9", "-"],
            ["4", "5", "6", "+"],
            ["1", "2", "3", "."],
            ["0", "(", ")", "="]
        ]

        for row_idx, row in enumerate(buttons):
            for col_idx, text in enumerate(row):
                btn = tk.Button(
                    btn_frame,
                    text=text,
                    font=("Arial", 16),
                    width=5,
                    height=2,
                    command=lambda t=text: self.click_btn(t)
                )
                btn.grid(row=row_idx, column=col_idx, padx=3, pady=3)

    def click_btn(self, text):
        current = self.var_text.get()
        if text == "C":
            # 清空
            self.var_text.set("")
        elif text == "←":
            # 退格删除
            self.var_text.set(current[:-1])
        elif text == "=":
            # 计算结果
            try:
                res = eval(current)
                self.var_text.set(str(res))
            except ZeroDivisionError:
                messagebox.showerror("错误", "不能除以0！")
                self.var_text.set("")
            except Exception:
                messagebox.showerror("错误", "表达式非法")
                self.var_text.set("")
        else:
            # 追加字符
            self.var_text.set(current + text)

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