【问题标题】:How to grab the text from a kivy button?如何从 kivy 按钮中获取文本?
【发布时间】:2022-01-02 03:58:34
【问题描述】:

我正在尝试为“投票应用程序”构建这个简单的 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 甚至没有启动)

非常感谢!

【问题讨论】:

    标签: python python-3.x user-interface kivy kivy-language


    【解决方案1】:

    您可以使用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]}")
    

    【讨论】:

    • 非常感谢!我试图在谷歌上找到答案,但我发现对于初学者来说太复杂了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多