简洁的Python计算器,直接上代码(用时10分钟):
import tkinter as tk
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + str(number))
def clear():
entry.delete(0, tk.END)
def calculate():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, str(result))
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "Error")
def key_press(event):
if event.keysym in ("Return", "="):
calculate()
elif event.keysym == "c":
clear()
elif event.keysym in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"):
button_click(event.keysym)
elif event.keysym in ("plus", "minus", "asterisk", "slash"):
button_click("+" if event.keysym == "plus" else "-" if event.keysym == "minus" else "*" if event.keysym == "asterisk" else "/")
root = tk.Tk()
root.title("Calculator")
root.geometry("340x400")
entry = tk.Entry(root, width=16, font=("Arial", 24), bd=10, relief=tk.SUNKEN, justify=tk.RIGHT)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10, ipady=10)
buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
]
row_val = 1
col_val = 0
for button_text in buttons:
tk.Button(root, text=button_text, width=4, height=2, font=("Arial", 20), command=lambda text=button_text: button_click(text) if text != "=" else calculate()).grid(row=row_val, column=col_val, padx=5, pady=5)
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1
tk.Button(root, text="C", width=4, height=2, font=("Arial", 20), command=clear).grid(row=row_val, column=col_val, padx=5, pady=5)
# 绑定键盘事件
root.bind("<KeyPress>", key_press)
root.mainloop()