【发布时间】: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