# 导入tkinter库，用于创建图形界面
import tkinter as tk
from tkinter import *

# 主窗口初始化
root = Tk()
root.title("简易计算器")  # 窗口标题
root.geometry("300x400")  # 窗口大小
root.resizable(False, False)  # 禁止调整窗口大小

# 用于存储输入的表达式
expression = ""

# 1. 按钮点击函数：把数字/符号输入到屏幕
def press(num):
    global expression
    expression = expression + str(num)
    equation.set(expression)

# 2. 等于按钮：计算结果
def equalpress():
    try:
        global expression
        total = str(eval(expression))  # 计算表达式
        equation.set(total)
        expression = total  # 保留结果，可继续计算
    except:
        equation.set("错误")
        expression = ""

# 3. 清除按钮：清空输入
def clear():
    global expression
    expression = ""
    equation.set("")

# 显示区域（文本框）
equation = StringVar()
entry = Entry(root, textvariable=equation, font=('Arial', 20), bd=10, justify=RIGHT)
entry.grid(row=0, column=0, columnspan=4, ipadx=8, ipady=10)

# ---------------------- 按钮布局 ----------------------
# 第一行：7 8 9 /
btn7 = Button(root, text='7', font=('Arial', 14), command=lambda: press(7), height=3, width=6)
btn7.grid(row=1, column=0)

btn8 = Button(root, text='8', font=('Arial', 14), command=lambda: press(8), height=3, width=6)
btn8.grid(row=1, column=1)

btn9 = Button(root, text='9', font=('Arial', 14), command=lambda: press(9), height=3, width=6)
btn9.grid(row=1, column=2)

divide = Button(root, text='/', font=('Arial', 14), command=lambda: press("/"), height=3, width=6)
divide.grid(row=1, column=3)

# 第二行：4 5 6 *
btn4 = Button(root, text='4', font=('Arial', 14), command=lambda: press(4), height=3, width=6)
btn4.grid(row=2, column=0)

btn5 = Button(root, text='5', font=('Arial', 14), command=lambda: press(5), height=3, width=6)
btn5.grid(row=2, column=1)

btn6 = Button(root, text='6', font=('Arial', 14), command=lambda: press(6), height=3, width=6)
btn6.grid(row=2, column=2)

multiply = Button(root, text='*', font=('Arial', 14), command=lambda: press("*"), height=3, width=6)
multiply.grid(row=2, column=3)

# 第三行：1 2 3 -
btn1 = Button(root, text='1', font=('Arial', 14), command=lambda: press(1), height=3, width=6)
btn1.grid(row=3, column=0)

btn2 = Button(root, text='2', font=('Arial', 14), command=lambda: press(2), height=3, width=6)
btn2.grid(row=3, column=1)

btn3 = Button(root, text='3', font=('Arial', 14), command=lambda: press(3), height=3, width=6)
btn3.grid(row=3, column=2)

minus = Button(root, text='-', font=('Arial', 14), command=lambda: press("-"), height=3, width=6)
minus.grid(row=3, column=3)

# 第四行：0 C = +
btn0 = Button(root, text='0', font=('Arial', 14), command=lambda: press(0), height=3, width=6)
btn0.grid(row=4, column=0)

clear_btn = Button(root, text='C', font=('Arial', 14), command=clear, height=3, width=6)
clear_btn.grid(row=4, column=1)

equal_btn = Button(root, text='=', font=('Arial', 14), command=equalpress, height=3, width=6)
equal_btn.grid(row=4, column=2)

plus = Button(root, text='+', font=('Arial', 14), command=lambda: press("+"), height=3, width=6)
plus.grid(row=4, column=3)

# 运行主循环
root.mainloop()