(1)计算任意一个算术表达式的加法、减法、除法以及乘法。(2)运算数为整数和小数 (3)人机界面自定义,要友好。如用户输入错误在计算之前可以修改。
时间: 2024-02-15 07:02:17 浏览: 74
好的,我可以为您提供一个基于Python的简单迷你计算器。以下是代码示例:
```python
from tkinter import *
def calculate():
expression = entry.get()
try:
result = eval(expression)
entry.delete(0, END)
entry.insert(0, result)
except:
entry.delete(0, END)
entry.insert(0, "Error")
def clear():
entry.delete(0, END)
root = Tk()
root.title("Mini Calculator")
entry = Entry(root, width=30, borderwidth=5)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
button_1 = Button(root, text="1", padx=20, pady=10, command=lambda: entry.insert(END, "1"))
button_2 = Button(root, text="2", padx=20, pady=10, command=lambda: entry.insert(END, "2"))
button_3 = Button(root, text="3", padx=20, pady=10, command=lambda: entry.insert(END, "3"))
button_4 = Button(root, text="4", padx=20, pady=10, command=lambda: entry.insert(END, "4"))
button_5 = Button(root, text="5", padx=20, pady=10, command=lambda: entry.insert(END, "5"))
button_6 = Button(root, text="6", padx=20, pady=10, command=lambda: entry.insert(END, "6"))
button_7 = Button(root, text="7", padx=20, pady=10, command=lambda: entry.insert(END, "7"))
button_8 = Button(root, text="8", padx=20, pady=10, command=lambda: entry.insert(END, "8"))
button_9 = Button(root, text="9", padx=20, pady=10, command=lambda: entry.insert(END, "9"))
button_0 = Button(root, text="0", padx=20, pady=10, command=lambda: entry.insert(END, "0"))
button_add = Button(root, text="+", padx=19, pady=10, command=lambda: entry.insert(END, "+"))
button_subtract = Button(root, text="-", padx=22, pady=10, command=lambda: entry.insert(END, "-"))
button_multiply = Button(root, text="*", padx=20, pady=10, command=lambda: entry.insert(END, "*"))
button_divide = Button(root, text="/", padx=22, pady=10, command=lambda: entry.insert(END, "/"))
button_decimal = Button(root, text=".", padx=21, pady=10, command=lambda: entry.insert(END, "."))
button_clear = Button(root, text="Clear", padx=60, pady=10, command=clear)
button_equal = Button(root, text="=", padx=20, pady=10, command=calculate)
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_0.grid(row=4, column=0)
button_decimal.grid(row=4, column=1)
button_add.grid(row=1, column=3)
button_subtract.grid(row=2, column=3)
button_multiply.grid(row=3, column=3)
button_divide.grid(row=4, column=3)
button_clear.grid(row=5, column=0, columnspan=2)
button_equal.grid(row=5, column=2, columnspan=2)
root.mainloop()
```
这个迷你计算器支持整数和小数的加减乘除运算。您可以自定义界面,例如更改窗口标题、按钮文本、尺寸等等。同时,如果您输入错误的表达式,也可以在计算之前进行修改。
阅读全文