import tkinter as tk
from tkinter import messagebox
def btn_click(value):
"""按钮点击事件处理"""
if value == '=':
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(tk.END, str(result))
except ZeroDivisionError:
messagebox.showerror(" 错误", "除数不能为零!")
entry.delete(0, tk.END)
except Exception as e:
messagebox.showerror(" 错误", "无效表达式")
entry.delete(0, tk.END)
elif value == 'C':
entry.delete(0, tk.END) # 清空输入框
elif value == '←':
entry.delete(len(entry.get()) - 1) # 删除最后一个字符
else:
entry.insert(tk.END, value) # 追加输入内容
# 创建主窗口
root = tk.Tk()
root.title(" 简易计算器")
root.geometry("300x400")
root.resizable(0, 0) # 禁止调整窗口大小
# 输入框
entry = tk.Entry(root, font=('Arial', 20), justify='right', bg='#f0f0f0')
entry.grid(row=0, column=0, columnspan=4, sticky='nsew', padx=5, pady=5)
# 按钮布局
buttons = [
('C', '←', '%', '/'),
('7', '8', '9', '*'),
('4', '5', '6', '-'),
('1', '2', '3', '+'),
('00', '0', '.', '=')
]
# 生成按钮
for row_idx, row in enumerate(buttons, start=1):
for col_idx, text in enumerate(row):
btn = tk.Button(root, text=text, font=('Arial', 16),
command=lambda t=text: btn_click(t),
bg='#e6e6e6', activebackground='#d9d9d9')
btn.grid(row=row_idx, column=col_idx, sticky='nsew', padx=2, pady=2)
# 特殊按钮颜色设置
if text in ['=', '+', '-', '*', '/']:
btn.config(bg='#ff9933', activebackground='#cc7a00')
elif text in ['C', '←']:
btn.config(bg='#ff6666', activebackground='#cc0000')
# 网格布局权重设置
for i in range(5):
root.grid_rowconfigure(i, weight=1)
for i in range(4):
root.grid_columnconfigure(i, weight=1)
root.mainloop()