请任意选择一个你熟悉的Python GUI库,实现一个科学计算器。
时间: 2024-02-27 17:52:58 浏览: 22
好的,我选择使用Tkinter库来实现一个科学计算器。以下是代码:
```python
import tkinter as tk
import math
class Calculator:
def __init__(self, master):
self.master = master
master.title("Scientific Calculator")
# create input and output text boxes
self.input_text = tk.StringVar()
self.input_text.set("")
self.input_label = tk.Label(master, textvariable=self.input_text, font=("Helvetica", 16), width=20, height=2, anchor="w")
self.input_label.grid(row=0, column=0, columnspan=4)
self.output_text = tk.StringVar()
self.output_text.set("")
self.output_label = tk.Label(master, textvariable=self.output_text, font=("Helvetica", 16), width=20, height=2, anchor="w")
self.output_label.grid(row=1, column=0, columnspan=4)
# create buttons
self.create_button("7", 2, 0)
self.create_button("8", 2, 1)
self.create_button("9", 2, 2)
self.create_button("/", 2, 3)
self.create_button("4", 3, 0)
self.create_button("5", 3, 1)
self.create_button("6", 3, 2)
self.create_button("*", 3, 3)
self.create_button("1", 4, 0)
self.create_button("2", 4, 1)
self.create_button("3", 4, 2)
self.create_button("-", 4, 3)
self.create_button("0", 5, 0)
self.create_button(".", 5, 1)
self.create_button("=", 5, 2)
self.create_button("+", 5, 3)
self.create_button("C", 6, 0)
self.create_button("sin", 6, 1)
self.create_button("cos", 6, 2)
self.create_button("tan", 6, 3)
def create_button(self, text, row, column):
button = tk.Button(self.master, text=text, width=5, height=2, font=("Helvetica", 16), command=lambda:self.button_click(text))
button.grid(row=row, column=column)
def button_click(self, text):
current_input = self.input_text.get()
if text == "C":
self.input_text.set("")
self.output_text.set("")
elif text == "=":
try:
result = eval(current_input)
self.output_text.set(str(result))
except:
self.output_text.set("Error")
elif text in ["sin", "cos", "tan"]:
try:
if current_input == "":
self.output_text.set("Error")
else:
result = eval("math." + text + "(" + current_input + ")")
self.output_text.set(str(result))
except:
self.output_text.set("Error")
else:
self.input_text.set(current_input + text)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
这个科学计算器有基本的加、减、乘、除、小数点、清除和等于按钮,同时还有三角函数sin、cos、tan的计算能力。用户可以在输入框中输入计算表达式,然后按下等于按钮进行计算,结果将显示在输出框中。如果用户输入的表达式不合法,输出框将显示"Error"。