Mohit Narwani
Mohit Narwani

Reputation: 207

How to print dynamic button text?

I have created the buttons dynamically in kivy. I want to print button text on on_release/on_press but when I am tapping the buttons. It's printing last element of the list while it should print text of button.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.properties import ObjectProperty
from kivy.factory import Factory

kv = '''
MyWidget:
    box: box
    BoxLayout:
        id: box
'''


class MyWidget(FloatLayout):
    box = ObjectProperty(None)

    def on_box(self, *args):
        a = ['Apple',"samsung","green"]
     
        for i in a:
      
            
            self.box.add_widget(Button(text=str(i),on_press=lambda x:self.uk(str(i))))
            
         
   
    def uk(self,instance):
     
        print(instance)
    def on_release(self, *largs):
        app = App.get_running_instance()
        app.button_texts.append(self.text)
        print(self.text)
           

Factory.register('MyWidget', cls=MyWidget)


class LoopApp(App):
    def build(self):
        return Builder.load_string(kv)


LoopApp().run()

Upvotes: 0

Views: 52

Answers (1)

John Anderson
John Anderson

Reputation: 38962

That is a common problem when building Buttons in a loop. The fix is to use another variable in your lambda for the loop variable. Try using this in that loop:

    for i in a:
        self.box.add_widget(Button(text=str(i), on_press=lambda x, y=i: self.uk(str(y))))

Upvotes: 1

Related Questions