[python]代码库
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout
class Calculator(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Calculator')
self.edit = QLineEdit()
self.edit.setReadOnly(True)
layout = QVBoxLayout()
layout.addWidget(self.edit)
buttons = [
['7', '8', '9', '+'],
['4', '5', '6', '-'],
['1', '2', '3', '*'],
['0', '.', '=', '/']
]
for row in buttons:
button_row = QHBoxLayout()
for label in row:
button = QPushButton(label)
button.clicked.connect(self.button_clicked)
button_row.addWidget(button)
layout.addLayout(button_row)
self.setLayout(layout)
def button_clicked(self):
button = self.sender()
if button.text() == '=':
self.edit.setText(str(eval(self.edit.text())))
else:
self.edit.setText(self.edit.text() + button.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
calculator = Calculator()
calculator.show()
sys.exit(app.exec_())
[代码运行效果截图]