[英]Python Generator Returns Last Item
I'm trying to loop through a CSV file and get an item from each row and insert it into the QLineEdit
in the GUI. 我正在尝试遍历CSV文件并从每一行中获取一项并将其插入GUI中的
QLineEdit
中。
When I click the button self.nextAppointment
it fills the field in, but always with the very last row's email address in the CSV file. 当我单击按钮
self.nextAppointment
它将填充该字段,但始终带有CSV文件中最后一行的电子邮件地址。 Subsequent clicks of the button do not appear to do anything. 随后单击该按钮似乎没有任何作用。
I'm thinking that I'm not creating/using the generator correctly, but I am not sure. 我以为我没有正确创建/使用生成器,但不确定。
How do I loop over the CSV file and get the fields I want returned so I can put that into the GUI on at a time for each row of the CSV. 如何遍历CSV文件并获取要返回的字段,以便可以每次将其放入CSV的每一行的GUI中。
Here is the relevant code: 以下是相关代码:
self.nextAppointment.clicked.connect(self.nextFunction)
def nextFunction(self):
self.emailGenerator = self.nextEmail()
for email in self.emailGenerator:
self.toField.setText(email)
def nextEmail(self):
with open('assigned_appt_leads.csv', 'rb') as infile:
rdr = csv.DictReader(infile, dialect='excel')
for line in rdr:
yield line['Email Address']
I've tested using the following and it gets the first email address, but pressing next does not change it to the next row's email address. 我已经使用以下方法进行了测试,它会获取第一个电子邮件地址,但是按next不会将其更改为下一行的电子邮件地址。
def nextFunction(self):
self.emailGenerator = self.nextEmail()
self.toField.setText(self.emailGenerator.next())
You are correctly looping and yielding. 您正在正确地循环并屈服。
What you are not doing is use the results correctly: 您没有做的是正确使用结果:
for email in self.emailGenerator:
self.toField.setText(email)
will replace any previous textual value each loop iteration . 将在每次循环迭代时替换任何先前的文本值。 This is why you see the last value only;
这就是为什么您只看到最后一个值的原因。 all previous calls to
self.toField.setText()
succeeded, but where then overwritten again by the next iteration. 之前对
self.toField.setText()
所有调用self.toField.setText()
成功,但是在下一次迭代中再次被覆盖。
You need to append to the existing text in the QLineEdit
widget instead. 您需要附加到
QLineEdit
小部件中的现有文本。 I suggest you use the .insert()
method: 我建议您使用
.insert()
方法:
for email in self.emailGenerator:
self.toField.insert(email + '\n')
If you wanted to assign items one by one to your field on user events, call next()
on self.emailGenerator
every time you need a new address: 如果要在用户事件中一个一栏地分配项到您的字段,请在每次需要新地址时在
self.emailGenerator
上调用next()
:
self.toField.insert(next(self.emailGenerator, ''))
instead of looping over it. 而不是循环遍历它。 The above sample line sets the field to
''
if you've run out of email addresses. 如果您的电子邮件地址用完了,上述示例行会将字段设置为
''
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.