使用 PushButton 遍历列表 - PyQt5

Looping through a list using PushButton - PyQt5

我目前正在尝试遍历预定义列表,在单击 pushButton_1 时将 label_1 更改为每个索引处的字符串。

我想我必须在循环中定义标签(如下所示),然后使用连接到按钮的函数来增加计数,但到目前为止我一直没有成功。

我的另一个想法是 'listen' 点击按钮,然后只有在满足该条件时才增加索引 - 这对我来说似乎更直观,但我不确定该怎么做这个。

from PyQt5 import QtCore, QtWidgets

list_1 = ['name1', 'name2', 'name3', 'name4']

def loop(count_value):
    return count_value + 1

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        MainWindow.setWindowTitle('List Looper')
        MainWindow.resize(540, 465)
        MainWindow.setMinimumSize(QtCore.QSize(200, 200))
        MainWindow.setMaximumSize(QtCore.QSize(200, 200))

        self.pushButton_1 = QtWidgets.QPushButton(MainWindow)
        self.pushButton_1.setGeometry(QtCore.QRect(10, 50, 141, 31))
        self.pushButton_1.clicked.connect(loop)
        self.pushButton_1.setText('Next Index')

        self.label_1 = QtWidgets.QLabel(MainWindow)
        self.label_1.setGeometry(QtCore.QRect(10, 10, 281, 16))

        count = 0
        while count < len(list_1):
            self.label_1.setText(list_1[count])

            # Run the loop() function upon button click to increase the count.

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

我试图找到类似的问题,但很多问题似乎都与替换小部件元素有关,而这不是我想要做的。

您的第二种方法是正确的,但您必须使计数器成为 class 的一个属性,并在每次调用与按钮的点击信号关联的方法时增加它:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        MainWindow.setWindowTitle("List Looper")
        MainWindow.resize(540, 465)
        MainWindow.setMinimumSize(QtCore.QSize(200, 200))
        MainWindow.setMaximumSize(QtCore.QSize(200, 200))

        self.pushButton_1 = QtWidgets.QPushButton(MainWindow)
        self.pushButton_1.setGeometry(QtCore.QRect(10, 50, 141, 31))
        self.pushButton_1.setText("Next Index")

        self.label_1 = QtWidgets.QLabel(MainWindow)
        self.label_1.setGeometry(QtCore.QRect(10, 10, 281, 16))

        self.counter = 0

        self.pushButton_1.clicked.connect(self.handle_clicked)

    def handle_clicked(self):
        if self.counter < len(list_1):
            self.label_1.setText(list_1[self.counter])
            self.counter += 1