import tkinter as tk
from tkinter import font

class CalculatorGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Python 计算器")
        self.root.geometry("400x550")
        self.root.configure(bg='#f0f0f0')
        
        # 设置字体
        self.display_font = font.Font(family="Arial", size=24, weight="bold")
        self.button_font = font.Font(family="Arial", size=16, weight="bold")
        
        # 初始化变量
        self.current_input = ""
        self.operation = None
        self.first_number = 0
        self.is_new_input = True
        
        # 创建界面
        self.create_widgets()
    
    def create_widgets(self):
        # 显示区域
        self.display_var = tk.StringVar(value="0")
        display_frame = tk.Frame(self.root, bg='#333333', height=100)
        display_frame.pack(fill=tk.X, padx=10, pady=10)
        
        display_label = tk.Label(
            display_frame,
            textvariable=self.display_var,
            font=self.display_font,
            bg='#333333',
            fg='white',
            anchor=tk.E,
            padx=20
        )
        display_label.pack(fill=tk.BOTH, expand=True)
        
        # 按钮区域
        buttons_frame = tk.Frame(self.root, bg='#f0f0f0')
        buttons_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 按钮布局
        button_layout = [
            ['C', '⌫', '%', '/'],
            ['7', '8', '9', '*'],
            ['4', '5', '6', '-'],
            ['1', '2', '3', '+'],
            ['00', '0', '.', '=']
        ]
        
        for i, row in enumerate(button_layout):
            buttons_frame.rowconfigure(i, weight=1)
            for j, text in enumerate(row):
                buttons_frame.columnconfigure(j, weight=1)
                
                # 设置按钮颜色
                if text in ['C', '⌫']:
                    bg_color = '#ff9999'
                elif text in ['/', '*', '-', '+', '=', '%']:
                    bg_color = '#ffcc99'
                else:
                    bg_color = '#ffffff'
                
                # 创建按钮
                button = tk.Button(
                    buttons_frame,
                    text=text,
                    font=self.button_font,
                    bg=bg_color,
                    fg='#333333',
                    relief=tk.RAISED,
                    bd=2,
                    command=lambda t=text: self.on_button_click(t)
                )
                button.grid(row=i, column=j, sticky='nsew', padx=2, pady=2)
                
                # 绑定键盘事件
                if text.isdigit() or text in ['+', '-', '*', '/', '.', '=']:
                    self.root.bind_all(text, lambda e, t=text: self.on_button_click(t))
                elif text == '⌫':
                    self.root.bind_all('<BackSpace>', lambda e: self.on_button_click('⌫'))
                elif text == 'C':
                    self.root.bind_all('<Escape>', lambda e: self.on_button_click('C'))
        
        # 绑定回车键
        self.root.bind_all('<Return>', lambda e: self.on_button_click('='))
        self.root.bind_all('<KP_Enter>', lambda e: self.on_button_click('='))
    
    def on_button_click(self, value):
        if value == 'C':
            self.clear_all()
        elif value == '⌫':
            self.backspace()
        elif value == '=':
            self.calculate()
        elif value in ['+', '-', '*', '/', '%']:
            self.set_operation(value)
        else:
            self.add_to_input(value)
    
    def add_to_input(self, value):
        if self.is_new_input:
            if value == '00':
                self.current_input = '0'
            else:
                self.current_input = value
            self.is_new_input = False
        else:
            if value == '00':
                if self.current_input != '0':
                    self.current_input += '00'
            elif value == '.':
                if '.' not in self.current_input:
                    self.current_input += '.'
            else:
                if self.current_input == '0':
                    self.current_input = value
                else:
                    self.current_input += value
        
        self.update_display()
    
    def set_operation(self, op):
        if self.current_input:
            if self.operation and not self.is_new_input:
                self.calculate()
            self.first_number = float(self.current_input)
            self.operation = op
            self.is_new_input = True
    
    def calculate(self):
        if not self.current_input or not self.operation:
            return
        
        second_number = float(self.current_input)
        result = 0
        
        try:
            if self.operation == '+':
                result = self.first_number + second_number
            elif self.operation == '-':
                result = self.first_number - second_number
            elif self.operation == '*':
                result = self.first_number * second_number
            elif self.operation == '/':
                if second_number == 0:
                    self.display_var.set("错误：除数不能为零")
                    return
                result = self.first_number / second_number
            elif self.operation == '%':
                result = self.first_number * second_number / 100
            
            # 处理结果显示
            if result.is_integer():
                result = int(result)
            else:
                result = round(result, 10)  # 限制小数位数
            
            self.display_var.set(str(result))
            self.current_input = str(result)
            self.operation = None
            self.is_new_input = True
            
        except Exception as e:
            self.display_var.set(f"错误: {e}")
    
    def clear_all(self):
        self.current_input = ""
        self.operation = None
        self.first_number = 0
        self.is_new_input = True
        self.display_var.set("0")
    
    def backspace(self):
        if self.current_input and not self.is_new_input:
            if len(self.current_input) > 1:
                self.current_input = self.current_input[:-1]
            else:
                self.current_input = "0"
                self.is_new_input = True
            self.update_display()
    
    def update_display(self):
        if not self.current_input:
            self.display_var.set("0")
        else:
            # 美化显示
            display_text = self.current_input
            if self.operation:
                display_text = f"{self.first_number} {self.operation} {display_text}"
            self.display_var.set(display_text)

# 运行计算器
if __name__ == "__main__":
    root = tk.Tk()
    calculator = CalculatorGUI(root)
    
    # 设置窗口图标和标题
    root.iconbitmap(default='')  # 可以在这里指定图标文件路径
    
    root.mainloop()