【问题标题】:Looping through a list using PushButton - PyQt5使用 PushButton 循环列表 - PyQt5
【发布时间】:2021-02-22 06:04:22
【问题描述】:

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

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

我的另一个想法是“倾听”按钮的点击,然后仅在满足该条件时才增加索引 - 这对我来说似乎更直观,但我不确定如何做到这一点。

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_())

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

【问题讨论】:

    标签: python loops user-interface pyqt5 qpushbutton


    【解决方案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.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 2021-12-11
      • 2018-07-16
      • 2017-04-10
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多