Search code examples
python-3.xbuttonindexingkivy

how can i index some buttons in a kivy file added by a loop from a python list?


i create 5 buttons in a kivy file, using a loop. when i try to print the clicked button's text, i always get the last one created. so i would index them. any suggest please? thanks

py file:

from kivy.app import App
from kivy.uix.screenmanager import Screen,ScreenManager
from kivy.lang import Builder
class Screen1(Screen):
    pass
class app(App):
    values = ('one', 'two', 'three', 'four', 'five')
    def build(self):
        sm=ScreenManager()
        sm.add_widget(Screen(name='screen_1'))
        return Builder.load_file('lab.kv')
    def print_that(self, i):
        print(i)
app().run()

kv file:

#:import Button kivy.uix.button.Button
ScreenManager:
    Screen:
        name:'screen1'
        BoxLayout:
            on_parent:
                [self.add_widget(Button(text=i,on_press=lambda x:app.print_that(i))) for i in app.values]

Solution

  • That is a common problem when using a lambda inside a loop. The lambda is not evaluated until it is executed by the Button press, so it ends up using the last value from the loop. You can fix this by adding a new variable to the lambda that equals the loop variable, like this:

    [self.add_widget(Button(text=i,on_press=lambda x, j=i:app.print_that(j))) for i in app.values]