Python-在PyQt5中循环创建按钮

时间:2019-02-28 13:46:24

标签: python python-3.x pyqt5

我一直在尝试根据PyQt5中变量的值创建X个按钮,但是我的方法不起作用。

我创建了一个带有循环的函数,其中X值为按钮的数量。

此代码(带有功能的注释)有效:

class Ui_MainWindow(object):

def setupUi(self, MainWindow):

    def createButtons(x):
        number_of_buttons = x
        table_set = 1
        distance_from_left = 5

        while table_set <= number_of_buttons:
            print(distance_from_left) #Check if the loop is runnig
            "self.pushButton_{} = QtWidgets.QPushButton(self.groupBox)".format(table_set)
            "self.pushButton_{}.setGeometry(QtCore.QRect({}, 15, 40, 35))".format(table_set, distance_from_left)
            "self.pushButton_{}.setText(\"{}\")".format(table_set, str(table_set).zfill(2))
            "self.pushButton_{}.setObjectName(\"pushButton_{}\")".format(table_set, table_set)
            table_set += 1
            distance_from_left += 45

    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(1366, 768)
    MainWindow.setAutoFillBackground(False)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
    self.groupBox.setGeometry(QtCore.QRect(0, 80, 531, 56))
    self.groupBox.setAutoFillBackground(False)
    self.groupBox.setObjectName("groupBox")
    #createButtons(3)
    self.pushButton_1 = QtWidgets.QPushButton(self.groupBox)
    self.pushButton_1.setGeometry(QtCore.QRect(5, 15, 40, 35))
    self.pushButton_1.setText("01")
    self.pushButton_1.setObjectName("pushButton_1")
    self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
    self.pushButton_2.setGeometry(QtCore.QRect(50, 15, 40, 35))
    self.pushButton_2.setText("02")
    self.pushButton_2.setObjectName("pushButton_2")
    self.pushButton_3 = QtWidgets.QPushButton(self.groupBox)
    self.pushButton_3.setGeometry(QtCore.QRect(95, 15, 40, 35))
    self.pushButton_3.setText("03")
    self.pushButton_3.setObjectName("pushButton_3")
    MainWindow.setCentralWidget(self.centralwidget)
    self.centralwidget.show()
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

此功能(功能正在运行,直接命令已注释)不起作用。在我看来,它们看起来一样。

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):

        def createButtons(x):
            number_of_buttons = x
            table_set = 1
            distance_from_left = 5

            while table_set <= number_of_buttons:
                print(distance_from_left) #Check if the loop is runnig
                "self.pushButton_{} = QtWidgets.QPushButton(self.groupBox)".format(table_set)
                "self.pushButton_{}.setGeometry(QtCore.QRect({}, 15, 40, 35))".format(table_set, distance_from_left)
                "self.pushButton_{}.setText(\"{}\")".format(table_set, str(table_set).zfill(2))
                "self.pushButton_{}.setObjectName(\"pushButton_{}\")".format(table_set, table_set)
                table_set += 1
                distance_from_left += 45

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1366, 768)
        MainWindow.setAutoFillBackground(False)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(0, 80, 531, 56))
        self.groupBox.setAutoFillBackground(False)
        self.groupBox.setObjectName("groupBox")
        createButtons(3)
        """
        self.pushButton_1 = QtWidgets.QPushButton(self.groupBox)
        self.pushButton_1.setGeometry(QtCore.QRect(5, 15, 40, 35))
        self.pushButton_1.setText("01")
        self.pushButton_1.setObjectName("pushButton_1")
        self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
        self.pushButton_2.setGeometry(QtCore.QRect(50, 15, 40, 35))
        self.pushButton_2.setText("02")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.groupBox)
        self.pushButton_3.setGeometry(QtCore.QRect(95, 15, 40, 35))
        self.pushButton_3.setText("03")
        self.pushButton_3.setObjectName("pushButton_3")
        """
        MainWindow.setCentralWidget(self.centralwidget)
        self.centralwidget.show()
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

所有按钮均未显示。有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

尝试一下:

import sys
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, 
                             QApplication, QPushButton)


class MainWindow(QMainWindow): 
    def __init__(self, x):                                         # x <-- 3
        super().__init__()

        self.centralwidget = QWidget()
        self.setCentralWidget(self.centralwidget)
        self.lay = QVBoxLayout(self.centralwidget)

        for i in range(x):                                          # <---
            self.btn = QPushButton('Button {}'.format(i +1), self)            
            text = self.btn.text()
            self.btn.clicked.connect(lambda ch, text=text : print("\nclicked--> {}".format(text)))
            self.lay.addWidget(self.btn)

        self.numButton = 4

        pybutton = QPushButton('Create a button', self)
        pybutton.clicked.connect(self.clickMethod)

        self.lay.addWidget(pybutton)
        self.lay.addStretch(1)

    def clickMethod(self):
        newBtn = QPushButton('New Button{}'.format(self.numButton), self)
        self.numButton += 1
        newBtn.clicked.connect(lambda : print("\nclicked===>> {}".format(newBtn.text())))
        self.lay.addWidget(newBtn)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = MainWindow(3)                                            # 3 --> x
    mainWin.show()
    sys.exit( app.exec_() )

enter image description here