I am making a video search app, and I came across this issue and I can not solve it. The user inputs keywords and the app returns video titles based on the search results. After that the app displays the results:
JavaScript
x
15
15
1
class SecondWindow(Screen):
2
def on_enter(self):
3
4
try:
5
self.ids.container.clear_widgets()
6
except:
7
pass
8
9
for i in range (len(vid_list)):
10
self.ids.container.add_widget(
11
OneLineAvatarIconListItem(text=vid_list[i], on_release =lambda v_id:self.send_link(vid_id[i]))
12
)
13
def send_link(self, v_id):
14
print(v_id) #always outputs the last vid_id no matter which one I click
15
This works perfectly and all the videos get displayed with unique titles. But I also set that it should send the videos_id based on the index, but it always sends the last one, no matter which one I click.
How could I solve this?
Advertisement
Answer
That is a common problem with defining a lambda
that uses a loop index. The fix is to define another index that equals the loop index. Like this:
JavaScript
1
5
1
for i in range (len(vid_list)):
2
self.ids.container.add_widget(
3
OneLineAvatarIconListItem(text=vid_list[i], on_release=lambda v_id, j=i:self.send_link(vid_list[j]))
4
)
5
Note the j=i
and the vid_list[j]
.