Home > Blockchain >  How to grab the text from a kivy button?
How to grab the text from a kivy button?

Time:11-24

I'm trying to build this simple GUI for a "voting app" where, by clicking the button with the candidate's ID, 1 will be added in the value of the ID key inside a dictionary. (counting votes on click basically)

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

CANDIDATES = {"T1031" : 0,"T2112" : 0, "T4561" : 0}



class MyLayout(BoxLayout):
    orientation = "Vertical"
    def __init__(self, **kwargs):
        super(MyLayout, self).__init__(**kwargs)
        for i in CANDIDATES:
            canditate = Button(text=i, on_press=self.button_clicked)
            self.add_widget(canditate)

    def button_clicked(self, obj):
        print("button pressed", obj)

class MyApp(App):
    def build(self):
        return MyLayout()


if __name__ == "__main__":
    MyApp().run()

So how can I grab the text displayed on the button ? (Also, if any of you guys know...how do I put an ID on the buttons? I tried with writing "id = i" but the GUI doesn't even start when I do that)

Many thanks in advance!

CodePudding user response:

You can access the text value from a button using the Button.text property:

def button_clicked(self, obj):
    # Note that obj here is a button object
    # You can access it's text value, for example, using obj.text
    CANDIDATES[obj.text]  = 1
    print(f"{obj.text}'s current vote count is now {CANDIDATES[obj.text]}")
  • Related