💻 源代码
import tkinter as tk
class Calculator:
def __init__(self):
self.window = tk.Tk()
self.window.title("计算器")
self.window.geometry("300x400")
self.display = tk.Entry(self.window, font=("Arial", 24), justify="right")
self.display.grid(row=0, column=0, columnspan=4, sticky="nsew", padx=5, pady=5)
buttons = [
('C', 1, 0), ('/', 1, 1), ('*', 1, 2), ('-', 1, 3),
('7', 2, 0), ('8', 2, 1), ('9', 2, 2), ('+', 2, 3),
('4', 3, 0), ('5', 3, 1), ('6', 3, 2), ('=', 3, 3),
('1', 4, 0), ('2', 4, 1), ('3', 4, 2), ('0', 4, 3),
('.', 5, 0),
]
for (text, row, col) in buttons:
btn = tk.Button(self.window, text=text, font=("Arial", 18),
command=lambda t=text: self.on_click(t))
btn.grid(row=row, column=col, sticky="nsew", padx=2, pady=2)
# 等号跨行
self.window.grid_columnconfigure(0, weight=1)
self.window.grid_columnconfigure(1, weight=1)
self.window.grid_columnconfigure(2, weight=1)
self.window.grid_columnconfigure(3, weight=1)
def on_click(self, char):
if char == 'C':
self.display.delete(0, tk.END)
elif char == '=':
try:
result = eval(self.display.get())
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")
else:
self.display.insert(tk.END, char)
def run(self):
self.window.mainloop()
if __name__ == '__main__':
calc = Calculator()
calc.run()