Home > Enterprise >  i always get same (last added) value, trying to get kivy's button's text, using python 3
i always get same (last added) value, trying to get kivy's button's text, using python 3

Time:01-25

i have a python3 script, and in a Kivy app i populate a Boxlayout with some Buttons, using a for loop to set Buttons texts from a list. i would like to get the right Button's text clicking each Button, but i always get same one. the last one. My little code:

dishes=['spaghetti','rice','fish','salad']
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class app(App):
    def build(self):
        self.box=BoxLayout()
        for dish in dishes:
            self.box.add_widget(Button(text=dish,on_press=lambda *args:print(dish)))
        return self.box
app().run()

CodePudding user response:

This way you definied anonymous functions with same body print(dish) for every button. Function is evauated on every click. So all buttons will execute print(dish) where dish is variable. Whatever you assign to this variable all buttons will print this value. In your case last value assigned to variable dish is 'salad', that's why all buttons prints 'salad'. It may look strange, but in fact variable dish is available also outside for loop. Python do not destroy this variable when for loop ends. It's a Python behaviour.

To get what you need I suggest replace line:

self.box.add_widget(Button(text=dish,on_press=lambda *args:print(dish)))

with

self.box.add_widget(Button(text=dish,on_press=lambda self:print(self.text)))

So every function will get self as function parameter (self = Button instance you just clicked), then you are able to print button's text attribute.

  • Related