import tkinter as tk
from tkinter import messagebox

class Calculator:
    def __init__(self, root):
        # 初始化主窗口
        self.root = root
        self.root.title("简易计算器")
        self.root.geometry("400x500")  # 窗口大小
        self.root.resizable(False, False)  # 禁止调整窗口大小
        
        # 存储输入的表达式
        self.expression = ""
        
        # 创建显示框
        self.create_display()
        
        # 创建按钮
        self.create_buttons()
    
    def create_display(self):
        """创建计算器的显示区域"""
        # 显示框样式
        self.display_var = tk.StringVar()
        display = tk.Entry(
            self.root,
            textvariable=self.display_var,
            font=("Arial", 20),
            justify="right",
            bd=10,
            relief="flat",
            bg="#f0f0f0"
        )
        # 布局显示框，占满宽度，留边距
        display.pack(fill="x", padx=20, pady=20, ipady=15)
    
    def create_buttons(self):
        """创建计算器的所有按钮"""
        # 按钮布局：按行定义按钮文本
        button_layout = [
            ["C", "←", "%", "/"],
            ["7", "8", "9", "*"],
            ["4", "5", "6", "-"],
            ["1", "2", "3", "+"],
            ["0", ".", "(", ")"],
            ["=", "", "", ""]
        ]
        
        # 创建按钮框架，方便布局
        button_frame = tk.Frame(self.root)
        button_frame.pack(padx=20, fill="both", expand=True)
        
        # 遍历布局创建按钮
        for row_idx, row in enumerate(button_layout):
            for col_idx, text in enumerate(row):
                if text:  # 跳过空文本的位置
                    # 设置按钮样式
                    btn = tk.Button(
                        button_frame,
                        text=text,
                        font=("Arial", 16),
                        bd=2,
                        relief="raised",
                        # 根据按钮文本设置不同的背景色
                        bg="#e0e0e0" if text in "0123456789.()" else "#ff9500" if text == "=" else "#f44336",
                        fg="white" if text in ["C", "←", "%", "/", "*", "-", "+", "=", "(", ")"] else "black",
                        # 绑定点击事件
                        command=lambda t=text: self.on_button_click(t)
                    )
                    # 按钮布局：按行列排列，占满空间
                    btn.grid(
                        row=row_idx,
                        column=col_idx,
                        padx=5,
                        pady=5,
                        sticky="nsew"
                    )
        
        # 设置每行每列的权重，让按钮自适应大小
        for i in range(6):
            button_frame.grid_rowconfigure(i, weight=1)
        for i in range(4):
            button_frame.grid_columnconfigure(i, weight=1)
    
    def on_button_click(self, text):
        """处理按钮点击事件"""
        if text == "C":
            # 清空表达式
            self.expression = ""
            self.display_var.set("")
        elif text == "←":
            # 退格：删除最后一个字符
            self.expression = self.expression[:-1]
            self.display_var.set(self.expression)
        elif text == "=":
            # 计算结果
            try:
                # 使用eval计算表达式，注意安全性（仅用于学习场景）
                result = eval(self.expression)
                # 处理小数末尾的0（如10.0显示为10）
                if isinstance(result, float) and result.is_integer():
                    result = int(result)
                self.display_var.set(result)
                # 将结果保存为新的表达式，方便继续计算
                self.expression = str(result)
            except ZeroDivisionError:
                messagebox.showerror("错误", "除数不能为0！")
                self.expression = ""
                self.display_var.set("")
            except:
                messagebox.showerror("错误", "输入的表达式无效！")
                self.expression = ""
                self.display_var.set("")
        else:
            # 数字/运算符输入
            self.expression += text
            self.display_var.set(self.expression)

if __name__ == "__main__":
    # 创建主窗口并运行计算器
    root = tk.Tk()
    calculator = Calculator(root)
    root.mainloop()