import tkinter as tk
from tkinter import ttk

# 按键点击事件，追加字符到输入框
def button_click(item):
    current_text = entry.get()
    entry.delete(0, tk.END)
    entry.insert(0, current_text + str(item))

# 清空输入框
def clear_all():
    entry.delete(0, tk.END)

# 计算表达式结果
def calculate():
    try:
        # eval计算数学表达式
        res = eval(entry.get())
        entry.delete(0, tk.END)
        entry.insert(0, str(res))
    except ZeroDivisionError:
        entry.delete(0, tk.END)
        entry.insert(0, "除零错误")
    except SyntaxError:
        entry.delete(0, tk.END)
        entry.insert(0, "语法错误")
    except Exception:
        entry.delete(0, tk.END)
        entry.insert(0, "ERROR")

# 创建主窗口
window = tk.Tk()
window.title("简易计算器")
window.geometry("320x420")
window.resizable(False, False)  # 固定窗口大小

# 输入显示框
entry = ttk.Entry(window, font=("Arial", 26), justify=tk.RIGHT)
entry.pack(padx=10, pady=10, fill=tk.BOTH)

# 按钮容器
btn_frame = ttk.Frame(window)
btn_frame.pack()

# 按钮定义：(显示文字,行,列)
button_list = [
    ("C", 0, 0), ("/", 0, 1), ("*", 0, 2), ("-", 0, 3),
    ("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("+", 1, 3),
    ("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("", 2, 3),
    ("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("", 3, 3),
    ("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("", 4, 3),
]

# 循环生成按钮
for text, row, col in button_list:
    if text == "":
        continue
    if text == "C":
        btn = ttk.Button(btn_frame, text=text, command=clear_all)
    elif text == "=":
        btn = ttk.Button(btn_frame, text=text, command=calculate)
    else:
        btn = ttk.Button(btn_frame, text=text, command=lambda t=text: button_click(t))
    btn.grid(row=row, column=col, padx=4, pady=4, ipadx=12, ipady=12)

# 启动主循环
window.mainloop()
