Skip to content
Advertisement

Is there a way to send a specific string to function in Kivy?

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:

class SecondWindow(Screen):
    def on_enter(self):

        try:
            self.ids.container.clear_widgets()
        except:
            pass

        for i in range (len(vid_list)):
            self.ids.container.add_widget(
                OneLineAvatarIconListItem(text=vid_list[i], on_release =lambda v_id:self.send_link(vid_id[i]))
            )
    def send_link(self, v_id):
        print(v_id) #always outputs the last vid_id no matter which one I click

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:

    for i in range (len(vid_list)):
        self.ids.container.add_widget(
            OneLineAvatarIconListItem(text=vid_list[i], on_release=lambda v_id, j=i:self.send_link(vid_list[j]))
        )

Note the j=i and the vid_list[j].

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement