python 计算器实现,包含标准、科学、程序员,使用Qt库实现带有界面操作的
时间: 2024-01-09 11:03:47 浏览: 92
下面是一个简单的示例代码,实现了Qt界面下的标准计算器功能:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLineEdit, QPushButton
import sys
import math
class Calculator(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Calculator')
self.setGeometry(300, 300, 250, 200)
self.grid = QGridLayout()
self.setLayout(self.grid)
self.result = QLineEdit()
self.grid.addWidget(self.result, 0, 0, 1, 4)
self.buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',
'C', '(', ')', 'sqrt',
'sin', 'cos', 'tan', 'pi',
'log', 'ln', 'e', '^'
]
self.add_buttons()
def add_buttons(self):
positions = [(i, j) for i in range(1, 7) for j in range(4)]
for position, button in zip(positions, self.buttons):
button_instance = QPushButton(button)
self.grid.addWidget(button_instance, *position)
button_instance.clicked.connect(lambda _, text=button: self.on_click(text))
def on_click(self, button):
if button == 'C':
self.result.setText('')
elif button == '=':
try:
self.result.setText(str(eval(self.result.text())))
except:
self.result.setText('Error')
elif button == 'sqrt':
num = math.sqrt(float(self.result.text()))
self.result.setText(str(num))
elif button == 'sin':
num = math.sin(float(self.result.text()))
self.result.setText(str(num))
elif button == 'cos':
num = math.cos(float(self.result.text()))
self.result.setText(str(num))
elif button == 'tan':
num = math.tan(float(self.result.text()))
self.result.setText(str(num))
elif button == 'pi':
self.result.setText(str(math.pi))
elif button == 'log':
num = math.log10(float(self.result.text()))
self.result.setText(str(num))
elif button == 'ln':
num = math.log(float(self.result.text()))
self.result.setText(str(num))
elif button == 'e':
self.result.setText(str(math.e))
elif button == '^':
num = float(self.result.text())
new_num = num ** 2
self.result.setText(str(new_num))
else:
self.result.setText(self.result.text() + button)
app = QApplication(sys.argv)
calc = Calculator()
calc.show()
sys.exit(app.exec_())
```
这个示例代码实现了基本的计算器功能,用户可以通过界面上的按钮进行数学运算,包括加减乘除、平方根、三角函数、对数函数、指数函数等。你可以在此基础上进一步扩展,实现更多功能,例如科学计算器、程序员计算器等。
阅读全文