编写一个简易计算器,主要包含如下功能: ①可实现加减乘除; ②可实现开根号功能; ③具有平方、立方计算功能; ④具有求余数功能; ⑤具有计算sin、cos、tan功能; ⑥界面中显示学号、姓名。
时间: 2024-03-25 20:41:22 浏览: 65
好的,我可以帮你实现一个简易计算器,并在界面中显示你的学号和姓名。以下是代码示例:
```python
import math
from tkinter import *
# 创建GUI界面
root = Tk()
root.title("计算器")
root.geometry("300x350")
# 显示学号和姓名
Label(root, text="学号:xxx").pack()
Label(root, text="姓名:xxx").pack()
Label(root, text="").pack()
# 定义计算器函数
def calculate():
num1 = float(entry1.get())
num2 = float(entry2.get())
operation = operator.get()
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
elif operation == "√":
result = math.sqrt(num1)
elif operation == "x²":
result = num1 ** 2
elif operation == "x³":
result = num1 ** 3
elif operation == "%":
result = num1 % num2
elif operation == "sin":
result = math.sin(num1)
elif operation == "cos":
result = math.cos(num1)
elif operation == "tan":
result = math.tan(num1)
entry3.delete(0, END)
entry3.insert(0, result)
# 创建输入框和标签
Label(root, text="请输入第一个数:").pack()
entry1 = Entry(root)
entry1.pack()
Label(root, text="请输入第二个数:").pack()
entry2 = Entry(root)
entry2.pack()
Label(root, text="请选择操作符:").pack()
operator = StringVar()
operator.set("+")
radiobutton1 = Radiobutton(root, text="+", variable=operator, value="+")
radiobutton2 = Radiobutton(root, text="-", variable=operator, value="-")
radiobutton3 = Radiobutton(root, text="*", variable=operator, value="*")
radiobutton4 = Radiobutton(root, text="/", variable=operator, value="/")
radiobutton5 = Radiobutton(root, text="√", variable=operator, value="√")
radiobutton6 = Radiobutton(root, text="x²", variable=operator, value="x²")
radiobutton7 = Radiobutton(root, text="x³", variable=operator, value="x³")
radiobutton8 = Radiobutton(root, text="%", variable=operator, value="%")
radiobutton9 = Radiobutton(root, text="sin", variable=operator, value="sin")
radiobutton10 = Radiobutton(root, text="cos", variable=operator, value="cos")
radiobutton11 = Radiobutton(root, text="tan", variable=operator, value="tan")
radiobutton1.pack()
radiobutton2.pack()
radiobutton3.pack()
radiobutton4.pack()
radiobutton5.pack()
radiobutton6.pack()
radiobutton7.pack()
radiobutton8.pack()
radiobutton9.pack()
radiobutton10.pack()
radiobutton11.pack()
Label(root, text="计算结果:").pack()
entry3 = Entry(root)
entry3.pack()
# 创建“计算”按钮
button = Button(root, text="计算", command=calculate)
button.pack()
root.mainloop()
```
你可以在代码中更改学号和姓名的显示内容。运行代码后,会弹出一个GUI界面,你可以在输入框中输入数字进行计算,选择不同的操作符进行不同的计算,点击“计算”按钮会在下方的输入框中显示计算结果。