简体   繁体   中英

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

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM