如何使用按钮一次遍历列表元素

问题描述

我有一个字符串列表,我想通过每次按一个按钮来打印它的下一个元素。

另外,我如何通过按下另一个按钮来打印列表的上一项?

这是示例代码:

from PyQt5 import QtCore,QtWidgets
import sys

class Main(QtWidgets.QMainWindow):

    def __init__(self):
      self.pushbutton = QtWidgets.QPushButton(self)
      self.pushbutton.move(20,20)
      self.list = ["first","second","third"]
      self.setGeometry(300,300,250,180)
      self.pushbutton.clicked.connect(self.showElements)
      self.show()
     
     def showElements(self):
      pass
      
app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

解决方法

您可以使用generators来获得您要求的功能

例如:

a = [1,2,3]

def myFunction():
    for item in a:
       yield item

# Get iterator
iterator = myFunction()

# Call this on every button push
nextItem = next(iterator)
print(nextItem)

这是一个正在运行的repl.it项目:

https://repl.it/@HarunYlmaz/generators-iterators

,

尝试一下:

import sys
from PyQt5 import QtCore,QtWidgets


class Example(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.centralWidget = QtWidgets.QWidget()
        self.setCentralWidget(self.centralWidget)

        self.list = ["first","second","third"]
        self.len_list = len(self.list) - 1
        self.index = 0

        self.label = QtWidgets.QLabel(self.list[self.index])
        
        button1 = QtWidgets.QPushButton('next')
        button1.clicked.connect(self.search_next)
        button2 = QtWidgets.QPushButton('previous')
        button2.clicked.connect(self.search_previous)
        
        layout = QtWidgets.QGridLayout(self.centralWidget)
        layout.addWidget(self.label,1,alignment=QtCore.Qt.AlignHCenter)
        layout.addWidget(button2,0)
        layout.addWidget(button1,1)        
     
    def search_next(self):
        if self.index >= self.len_list:
            self.index = 0
        else:
            self.index += 1
        self.label.setText(self.list[self.index])
        
    def search_previous(self):
        if self.index <= 0:
            self.index = self.len_list
        else:
            self.index -= 1
        self.label.setText(self.list[self.index])        
      
      
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...