import tkinter as tk
from tkinter import messagebox

class ModernCalculator:
    def __init__(self, root):
        self.root = root
        self.root.title("现代计算器")
        self.root.geometry("320x450")
        self.root.configure(bg='#1e1e1e') # 深色背景

        self.equation = ""
        
        # 显示框
        self.display = tk.Entry(root, font=("Microsoft YaHei", 24), borderwidth=0, 
                                relief="flat", justify='right', bg='#1e1e1e', fg='white')
        self.display.pack(pady=20, padx=10, fill="x")

        # 按钮区域
        self.btn_frame = tk.Frame(root, bg='#1e1e1e')
        self.btn_frame.pack()

        # 按钮样式定义
        buttons = [
            'C', 'DEL', '%', '/',
            '7', '8', '9', '*',
            '4', '5', '6', '-',
            '1', '2', '3', '+',
            '0', '.', '='
        ]

        row, col = 0, 0
        for btn_text in buttons:
            self.create_button(btn_text, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def create_button(self, text, row, col):
        # 根据按键类型设置颜色
        if text == '=':
            bg_color = '#2ecc71' # 绿色
            width, height = 16, 2
        elif text in ['+', '-', '*', '/', 'C', 'DEL', '%']:
            bg_color = '#34495e' # 深蓝灰
            width, height = 7, 2
        else:
            bg_color = '#3d3d3d' # 灰色
            width, height = 7, 2

        btn = tk.Button(self.btn_frame, text=text, width=width, height=height,
                        font=("Microsoft YaHei", 12, "bold"),
                        bg=bg_color, fg='white', borderwidth=0,
                        command=lambda: self.on_click(text))
        
        # 特殊处理等号跨列
        if text == '=':
            btn.grid(row=row, column=col, columnspan=2, sticky="nsew", padx=2, pady=2)
        else:
            btn.grid(row=row, column=col, padx=2, pady=2)

    def on_click(self, char):
        if char == 'C':
            self.equation = ""
        elif char == 'DEL':
            self.equation = self.equation[:-1]
        elif char == '=':
            try:
                self.equation = str(eval(self.equation))
            except:
                self.equation = "Error"
        else:
            self.equation += str(char)
        
        self.display.delete(0, tk.END)
        self.display.insert(0, self.equation)

if __name__ == "__main__":
    root = tk.Tk()
    app = ModernCalculator(root)
    root.mainloop()