import tkinter as tk
from tkinter import messagebox

class BlackCalculator:
    def __init__(self, root):
        self.root = root
        self.root.title("黑色极简计算器")
        self.root.geometry("320x480")
        self.root.configure(bg="#1A1A1A")  # 深黑色背景
        self.root.resizable(False, False)

        self.equation = ""
        
        # 显示屏设置
        self.display = tk.Entry(
            root, font=("Arial", 30), 
            bg="#1A1A1A", fg="#FFFFFF", 
            borderwidth=0, justify="right"
        )
        self.display.grid(row=0, column=0, columnspan=4, padx=10, pady=30, sticky="nsew")

        # 按钮布局
        buttons = [
            'C', '(', ')', '/',
            '7', '8', '9', '*',
            '4', '5', '6', '-',
            '1', '2', '3', '+',
            '0', '.', '=', ''
        ]

        row_val = 1
        col_val = 0

        for button in buttons:
            if button == '':
                continue
            
            # 区分功能键和数字键的颜色
            if button in ['C', '/', '*', '-', '+', '=', '(', ')']:
                btn_color = "#333333"  # 深灰色
                fg_color = "#FF9500"  # 橙色文字
            else:
                btn_color = "#252525"  # 浅黑色
                fg_color = "#FFFFFF"  # 白色文字

            action = lambda x=button: self.click_event(x)
            
            btn = tk.Button(
                root, text=button, width=5, height=2, 
                font=("Arial", 14, "bold"),
                bg=btn_color, fg=fg_color,
                activebackground="#404040", activeforeground="white",
                relief="flat", command=action
            )
            
            # 特殊处理等号：让它占据两个位置或者保持美观
            btn.grid(row=row_val, column=col_val, padx=5, pady=5, sticky="nsew")
            
            # 绑定鼠标悬停效果
            btn.bind("<Enter>", lambda e, b=btn: b.configure(bg="#404040"))
            btn.bind("<Leave>", lambda e, b=btn, c=btn_color: b.configure(bg=c))

            col_val += 1
            if col_val > 3:
                col_val = 0
                row_val += 1

    def click_event(self, key):
        if key == "=":
            try:
                # 计算结果
                result = str(eval(self.equation))
                self.display.delete(0, tk.END)
                self.display.insert(tk.END, result)
                self.equation = result
            except Exception:
                messagebox.showerror("错误", "无效的表达式")
                self.clear_screen()
        elif key == "C":
            self.clear_screen()
        else:
            self.equation += str(key)
            self.display.delete(0, tk.END)
            self.display.insert(tk.END, self.equation)

    def clear_screen(self):
        self.equation = ""
        self.display.delete(0, tk.END)

if __name__ == "__main__":
    root = tk.Tk()
    # 针对部分系统调整按钮点击后的焦点颜色
    root.option_add('*Font', 'Arial 12')
    calc = BlackCalculator(root)
    root.mainloop()