如何在python中多次追加同一元素?

时间:2019-07-17 14:20:39

标签: python list pyqt append qlineedit

我正在创建一个具有NUMBER行编辑的GUI。但是,为了获取其中写入的文本,我尝试制作一个LineEdits列表,并为每次迭代向列表中追加/添加一个LineEdit元素。 然后,我尝试将当前项目添加到布局中,并在继续按下时可以将NAME_LIST更改为重命名lineEdits。

我试图写出self.lineEditRename的长度,似乎同一项目不能多次附加。是这样吗,我该如何解决? 运行文件时出现此错误。

layout.addWidget(self.lineEditRename[i],2,i)
IndexError: list index out of range

请帮助:)

# NAME LIST
self.NAME_LIST = []
for i in range(0, NUMBER):
    self.NAME_LIST.append("NUMBER: "+ str(i))

for i in range(0,NUMBER+1):
            print(i)
            if (i==0):
                layout.addWidget(QtWidgets.QLabel("Rename: "),2,i))
            else:
                layout.addWidget(QtWidgets.QLabel(self.NAME_LIST[i-1]),0,i)
                self.lineEditRename = [QtWidgets.QLineEdit(self), QtWidgets.QLineEdit(self)]
                self.lineEditRename.append(QtWidgets.QLineEdit(self))
                layout.addWidget(self.lineEditRename[i-1],2,i)

self.QContinueButton = QtWidgets.QPushButton("Continue")
self.QContinueButton.clicked.connect(lambda: self.windowtwo(NUMBER))
layout.addWidget(self.QContinueButton,10,2)


def windowtwo(self, NUMBER):
        for i in range(1,NUMBER+1):
            print(self.lineEditRename[i].text())
            self.NAME_LIST[i-1]=self.lineEditRename[i].text()
        self.switch_window.emit()

1 个答案:

答案 0 :(得分:0)

您的问题是由于此行self.lineEditRename = [QtWidgets.QLineEdit(self), QtWidgets.QLineEdit(self)]self.lineEditRename的长度将始终为3,因此一旦i变为3,您将得到一个IndexError: list index out of range

您是要这样做吗?

self.lineEditRename = [QtWidgets.QLineEdit(self), QtWidgets.QLineEdit(self)]
for i in range(0,NUMBER+1):
    print(i)
    if (i==0):
        layout.addWidget(QtWidgets.QLabel("Rename: "),2,i))
    else:
        layout.addWidget(QtWidgets.QLabel(self.NAME_LIST[i-1]),0,i)
        self.lineEditRename.append(QtWidgets.QLineEdit(self))
        layout.addWidget(self.lineEditRename[i],2,i)