python窗体计算机
import tkinter as tk
# 创建主窗口
root = tk.Tk()
root.title("云黑课堂例子——简单计算机")
# 输入框
entry = tk.Entry(root, width=16, font=('Arial', 24), borderwidth=2)
entry.grid(row=0, column=0, columnspan=4)
# 按钮点击事件
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + str(number))
def button_clear():
entry.delete(0, tk.END)
def button_equal():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, result)
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "错误")
# 创建按钮
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', 'C', '=', '+'
]
row_val = 1
col_val = 0
for button in buttons:
if button == 'C':
btn = tk.Button(root, text=button, padx=20, pady=20, command=button_clear)
elif button == '=':
btn = tk.Button(root, text=button, padx=20, pady=20, command=button_equal)
else:
btn = tk.Button(root, text=button, padx=20, pady=20, command=lambda b=button: button_click(b))
btn.grid(row=row_val, column=col_val)
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1
# 启动主循环
root.mainloop()