设计一个有GU1 界面的简单计算器。基本要求:输入两个数据,程序能够完成两个数的加、减、乘和除运算,并显示运算结果
时间: 2024-01-21 07:20:02 浏览: 23
好的,我可以给你提供一个简单的GUI计算器的代码,使用Python的Tkinter库来实现:
```python
from tkinter import *
def calculate():
num1 = float(entry1.get())
num2 = float(entry2.get())
if operation.get() == "+":
result = num1 + num2
elif operation.get() == "-":
result = num1 - num2
elif operation.get() == "*":
result = num1 * num2
elif operation.get() == "/":
result = num1 / num2
label_result.config(text="Result: %.2f" % result)
root = Tk()
root.title("Simple Calculator")
entry1 = Entry(root, width=10)
entry1.grid(row=0, column=0)
operation = StringVar()
operation.set("+")
operator = OptionMenu(root, operation, "+", "-", "*", "/")
operator.grid(row=0, column=1)
entry2 = Entry(root, width=10)
entry2.grid(row=0, column=2)
button = Button(root, text="Calculate", command=calculate)
button.grid(row=1, column=1)
label_result = Label(root, text="Result: ")
label_result.grid(row=2, column=1)
root.mainloop()
```
该代码创建了一个简单的GUI计算器窗口,包含两个输入框、一个下拉菜单和一个计算按钮。当用户点击计算按钮时,程序将获取两个输入框中的值和所选的操作符,根据操作符来计算结果,并在结果标签中显示结果。
这个计算器可以进行简单的加、减、乘和除运算。你可以根据需要进一步扩展功能,如添加更多的操作符或对输入进行验证等。