如何从 kivy 按钮中获取文本?

How to grab the text from a kivy button?

我正在尝试为“投票应用程序”构建这个简单的 GUI,通过单击带有候选人 ID 的按钮,+1 将添加到字典内 ID 键的值中。 (基本按点击计票)

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

那么我怎样才能抓取按钮上显示的文本呢? (此外,如果你们有人知道……我如何在按钮上放置 ID?我尝试编写“id = i”,但当我这样做时 GUI 甚至没有启动)

非常感谢!

您可以使用 Button.text 属性:

从按钮访问文本值
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]}")