PyQt5学习6-第一个应用-简单计算器 发表于 2018-07-21 | 分类于 PyQt5 结合QPushButton,QLineEdit,QGridLayout能够编写一个简单的计算器软件,可以满足日常基本需求。 calculator1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162#!/usr/bin/python3#-*- coding: utf-8 -*-import sysfrom PyQt5.QtWidgets import QWidget,QPushButton,QLineEdit,QApplication,QGridLayoutclass ex(QWidget): def __init__(self): super(ex, self).__init__() self.initUI() def initUI(self): self.expression = '' grid = QGridLayout() self.setLayout(grid) self.display = QLineEdit('0') self.display.setReadOnly(True) self.display.setMaxLength(15) grid.addWidget(self.display,0,0,1,4) names = ['Clear','Back','','Close', '7','8','9','/', '4','5','6','*', '1','2','3','-', '0','.','=','+'] positions = [(i+1,j) for i in range(5) for j in range(4)] for pos, name in zip(positions, names): if name == '': continue button = QPushButton(name) button.clicked.connect(self.buttonClicked) grid.addWidget(button, *pos) self.setWindowTitle('Calcular') self.show() def buttonClicked(self): text = self.sender().text() if text in '+-*/': self.expression = self.expression + text elif text == '=': self.expression = str(eval(self.expression)) elif text == 'Back': self.expression = self.expression[0:len(self.expression)-1] elif text == 'Clear': self.expression = '0' elif text == 'Close': self.close() else: self.expression = text if self.expression == '0' else self.expression+text self.display.setText(self.expression)if __name__ == '__main__': app = QApplication(sys.argv) e = ex() sys.exit(app.exec_()) 结果