请任意选择一个你熟悉的Python GUI库,实现一个科学计算器。要求至少能实现加运算、减运算、乘运算、除运算、幂运算和取余运算。
时间: 2024-04-28 21:23:43 浏览: 96
基于Python编写一个计算器程序,实现简单的加减乘除和取余二元运算
5星 · 资源好评率100%
好的,我选择使用PyQt5库来实现一个科学计算器。以下是代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QGridLayout, QLineEdit, QVBoxLayout
class Calculator(QWidget):
def __init__(self):
super().__init__()
# 设置窗口标题和大小
self.setWindowTitle("Scientific Calculator")
self.resize(300, 400)
# 设置计算器的布局
self.layout = QVBoxLayout()
# 添加一个文本框,用于显示输入和输出内容
self.textbox = QLineEdit(self)
self.textbox.setReadOnly(True)
self.layout.addWidget(self.textbox)
# 添加数字和运算符按钮
grid = QGridLayout()
self.buttons = {}
button_labels = [
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", ".", "C", "/",
"^", "%"
]
positions = [(i, j) for i in range(4) for j in range(4)]
for position, label in zip(positions, button_labels):
if label == "C":
button = QPushButton(label, self, clicked=self.clear_textbox)
else:
button = QPushButton(label, self, clicked=lambda label=label: self.append_textbox(label))
grid.addWidget(button, *position)
self.buttons[label] = button
# 添加幂运算和取余运算按钮
self.pow_button = QPushButton("^", self, clicked=lambda label="^": self.append_textbox(label))
self.mod_button = QPushButton("%", self, clicked=lambda label="%": self.append_textbox(label))
grid.addWidget(self.pow_button, 0, 3)
grid.addWidget(self.mod_button, 1, 3)
self.layout.addLayout(grid)
self.setLayout(self.layout)
def clear_textbox(self):
self.textbox.setText("")
def append_textbox(self, label):
current_text = self.textbox.text()
if label == "C":
self.textbox.setText("")
elif label == "=":
try:
result = eval(current_text)
self.textbox.setText(str(result))
except:
self.textbox.setText("Error")
else:
self.textbox.setText(current_text + label)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建一个计算器窗口
self.calculator = Calculator()
# 将计算器窗口添加到主窗口
self.setCentralWidget(self.calculator)
# 设置主窗口的标题
self.setWindowTitle("Calculator")
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
```
这个科学计算器有基本的加、减、乘、除、幂和取余运算能力,同时有清除按钮和等于按钮。用户可以在输入框中输入计算表达式,然后按下等于按钮进行计算,结果将显示在输出框中。如果用户输入的表达式不合法,输出框将显示"Error"。
阅读全文