参考: PyQt5中文教程
''' 思路: 设置按钮, 添加到网格布局中 为按钮添加功能 解决问题: 除零 报错 等号后 直接按数字问题 ''' import sys from PyQt5.QtWidgets import QWidget, QApplication, QLineEdit, QPushButton, QGridLayout, QHBoxLayout, QVBoxLayout from PyQt5.QtGui import QIcon, QFont from PyQt5.QtCore import Qt class Calculater(QWidget): def __init__(self): super().__init__() self.initUI() # 初始化属性值 self.reset() def initUI(self): # 创建窗口标题 self.setWindowTitle("计算器") self.setWindowIcon(QIcon("icon.ico")) # 网格布局 gridLayout = QGridLayout() # 设置文本 self.lineEdit = QLineEdit("0") # 文本从右面开始显示 self.lineEdit.setAlignment(Qt.AlignRight) # 禁止直接输入 只读 self.lineEdit.setReadOnly(True) # 设置显示文本得到字体 self.lineEdit.setFont(QFont("Times", 20)) # 设置最多显示的数字长度 self.lineEdit.setMaxLength(15) # 创建按钮 # btn = QPushButton() # 创建 names = [ "AC", "Del", "", "close", "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "=", "/", ] grids = [(i, j) for i in range(1, 6) for j in range(0, 4)] # 将单行文本框加入布局 gridLayout.addWidget(self.lineEdit, 0, 0, 1, 4) # 构建表格 for grid, name in zip(grids, names): btn = QPushButton(name) btn.resize(btn.sizeHint()) btn.setFixedSize(60, 30) btn.clicked.connect(self.buttonClick) # if name == "0": # # 后边的四个参数分别是 行 , 列, 行跨度, 列跨度 # print(grid[1]) # gridLayout.addWidget(QPushButton(name), grid[0], grid[1], 1, 2) # elif name == ".": # gridLayout.addWidget(QPushButton(name), grid[0], grid[1]+1, 1, 1) # elif name == "=": # btn = QPushButton(name) # # gridLayout.addWidget(btn, grid[0], grid[1], 2, 1) # else: # gridLayout.addWidget( QPushButton(name), *grid) if name == "": continue else: gridLayout.addWidget(btn, *grid) self.setLayout(gridLayout) self.show() def buttonClick(self): # 获取number text = self.sender().text() if text in "+-*/": self.string += text # 用来存储表达式 self.number = "" # 在这里如果继续执行的话在界面展示会有问题所以退出 self.last = text return # 用eval的话不需要判断点 # elif text == ".": elif text == "=": self.resault() return elif text == "AC": self.reset() elif text == "Del": self.deleat() elif text == "close": self.close() else: # 如果之前已经按了等号在按数字的话清空之前的值 if self.last == "=" and type(eval(text)) == int: self.reset() # 除零判断 elif self.last == "/" and text == "0": self.number = "error" self.lineEdit.setText(self.number) return # 如果 self.number != 0 self.number = self.number + text 否则 self.number = text self.number = self.number + text if self.number != "0" else text self.string += text # 用来记录按键 self.lineEdit.setText(self.number) def resault(self): self.lineEdit.setText(str(eval(self.string))) # 这一个设置每次运算完后直接将结果改变 self.string = str(eval(self.string)) self.number = "" self.last = "=" def reset(self): #重置用来接收按钮数字 self.number = "0" # 重置用来存储按钮数字和运算符的字符串 self.string = "" self.last = "" self.symbol = "" def deleat(self): self.string = self.string[0:-1] # self.number = self.number[0:-1] # # 如果self.number 的删除后为空则设置为0 # if not self.number: # self.number = "0" # 间写 self.number = self.number[0: -1] if self.number[0: -1] else "0" if __name__ == "__main__": app = QApplication(sys.argv) ex = Calculater() sys.exit(app.exec_())