5.15每日总结
今天学习一些python的知识,尝试用python写一个计算机,
代码如下:
import tkinter as tk
import math
def calculate():
try:
expression = entry.get()
result = eval(expression)
entry.delete(0, tk.END)
entry.insert(0, str(result))
except:
entry.delete(0, tk.END)
entry.insert(0, "Error")
def backspace():
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current[:-1])
def clear():
entry.delete(0, tk.END)
root = tk.Tk()
root.title("Calculator")
entry = tk.Entry(root, width=25, font=('Arial', 16))
entry.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
button_1 = tk.Button(root, text='1', command=lambda: entry.insert(tk.END, '1'))
button_1.grid(row=1, column=0, padx=5, pady=5)
# ...
button_divide = tk.Button(root, text='/', command=lambda: entry.insert(tk.END, '/'))
button_divide.grid(row=4, column=3, padx=5, pady=5)
button_sqrt = tk.Button(root, text='√x', command=lambda: entry.insert(tk.END, 'math.sqrt('))
button_sqrt.grid(row=1, column=4, padx=5, pady=5)
button_power = tk.Button(root, text='x^y', command=lambda: entry.insert(tk.END, '**'))
button_power.grid(row=2, column=4, padx=5, pady=5)
button_reciprocal = tk.Button(root, text='1/x', command=lambda: entry.insert(tk.END, '1/'))
button_reciprocal.grid(row=3, column=4, padx=5, pady=5)
button_negate = tk.Button(root, text='+/-', command=lambda: entry.insert(0, '-'))
button_negate.grid(row=4, column=4, padx=5, pady=5)
button_backspace = tk.Button(root, text='←', command=backspace)
button_backspace.grid(row=5, column=0, padx=5, pady=5)
button_clear = tk.Button(root, text='C', command=clear)
button_clear.grid(row=5, column=1, padx=5, pady=5)
button_equals = tk.Button(root, text='=', command=calculate)
button_equals.grid(row=5, column=2, columnspan=2, padx=5, pady=5)
root.mainloop()