# 导入自带的GUI库
import tkinter as tk
from tkinter import messagebox

# 主窗口初始化
root = tk.Tk()
root.title("简易计算器")
root.geometry("300x400")  # 窗口大小
root.resizable(False, False)  # 禁止缩放

# 输入显示框
entry_text = tk.StringVar()
entry = tk.Entry(
    root,
    textvariable=entry_text,
    font=("Arial", 20),
    justify="right",  # 文字右对齐
    bd=10,
    bg="#f0f0f0"
)
entry.grid(row=0, column=0, columnspan=4, sticky="nsew")

# 按钮点击事件


def click_button(item):
    current = entry_text.get()
    entry_text.set(current + str(item))

# 清空输入框


def clear_all():
    entry_text.set("")

# 删除最后一位


def delete_last():
    current = entry_text.get()
    entry_text.set(current[:-1])

# 计算结果


def calculate():
    try:
        # 把 × ÷ 替换成 Python 能识别的符号
        expression = entry_text.get().replace("×", "*").replace("÷", "/")
        result = eval(expression)  # 执行计算
        entry_text.set(str(result))
    except Exception:
        messagebox.showerror("错误", "输入格式不正确！")
        clear_all()


# 按钮布局
buttons = [
    ("C", 1, 0), ("Del", 1, 1), ("÷", 1, 2), ("×", 1, 3),
    ("7", 2, 0), ("8", 2, 1), ("9", 2, 2), ("-", 2, 3),
    ("4", 3, 0), ("5", 3, 1), ("6", 3, 2), ("+", 3, 3),
    ("1", 4, 0), ("2", 4, 1), ("3", 4, 2), ("=", 4, 3),
    ("0", 5, 0), (".", 5, 1)
]

# 循环创建按钮
for (text, row, col) in buttons:
    if text == "=":
        btn = tk.Button(
            root, text=text, font=("Arial", 16),
            command=calculate, bg="#4CAF50", fg="white"
        )
    elif text == "C":
        btn = tk.Button(
            root, text=text, font=("Arial", 16),
            command=clear_all, bg="#f44336", fg="white"
        )
    elif text == "Del":
        btn = tk.Button(
            root, text=text, font=("Arial", 16),
            command=delete_last, bg="#ff9800"
        )
    else:
        btn = tk.Button(
            root, text=text, font=("Arial", 16),
            command=lambda t=text: click_button(t)
        )
    btn.grid(row=row, column=col, sticky="nsew", padx=1, pady=1)

# 让按钮自适应拉伸
for i in range(6):
    root.grid_rowconfigure(i, weight=1)
for i in range(4):
    root.grid_columnconfigure(i, weight=1)

# 启动主循环
root.mainloop()
