import tkinter as tk
from tkinter import font

# 主窗口
root = tk.Tk()
root.title("简易计算器")
root.geometry("320x420")  # 窗口大小
root.resizable(False, False)  # 禁止缩放

# 定义样式
my_font = font.Font(size=16)
display_font = font.Font(size=24)

# 显示框
display_var = tk.StringVar()
display_var.set("")

display = tk.Label(
    root,
    textvariable=display_var,
    font=display_font,
    bg="#f0f0f0",
    anchor="e",  # 右对齐
    padx=10,
    pady=20
)
display.pack(fill="x", padx=10, pady=10)

# 按钮点击逻辑


def button_click(char):
    current = display_var.get()
    display_var.set(current + str(char))


def button_clear():
    display_var.set("")


def button_delete():
    current = display_var.get()
    display_var.set(current[:-1])


def button_equal():
    try:
        result = eval(display_var.get())  # 计算表达式
        display_var.set(str(result))
    except:
        display_var.set("错误")


# 按钮布局
btn_frame = tk.Frame(root)
btn_frame.pack(padx=10, pady=5)

# 按钮文本、行、列、宽度
buttons = [
    ("C", 0, 0, 1), ("←", 0, 1, 1), ("/", 0, 2, 1), ("*", 0, 3, 1),
    ("7", 1, 0, 1), ("8", 1, 1, 1), ("9", 1, 2, 1), ("-", 1, 3, 1),
    ("4", 2, 0, 1), ("5", 2, 1, 1), ("6", 2, 2, 1), ("+", 2, 3, 1),
    ("1", 3, 0, 1), ("2", 3, 1, 1), ("3", 3, 2, 1), ("=", 3, 3, 1),
    ("0", 4, 0, 2), (".", 4, 2, 1)
]

# 循环创建按钮
for (text, row, col, span) in buttons:
    if text == "C":
        btn = tk.Button(btn_frame, text=text, font=my_font, width=5, height=2,
                        command=button_clear, bg="#ff7070")
    elif text == "←":
        btn = tk.Button(btn_frame, text=text, font=my_font, width=5, height=2,
                        command=button_delete, bg="#ffb347")
    elif text == "=":
        btn = tk.Button(btn_frame, text=text, font=my_font, width=5, height=2,
                        command=button_equal, bg="#87ceeb")
    elif text in "+-*/":
        btn = tk.Button(btn_frame, text=text, font=my_font, width=5, height=2,
                        command=lambda t=text: button_click(t), bg="#dcdcdc")
    else:
        btn = tk.Button(btn_frame, text=text, font=my_font, width=5, height=2,
                        command=lambda t=text: button_click(t))

    btn.grid(row=row, column=col, columnspan=span, padx=3, pady=3)

# 运行主循环
root.mainloop()
