如何获取 kivy 按钮的 Id 和 Text 值作为字符串?

2023-12-06

我有一个带有多个按钮的应用程序,我需要在按下按钮时以字符串形式获取按钮的 id 和文本值。然后,抓取的按钮 ID 和文本值将被传递到另一个函数以进行进一步处理。为了简单起见,我编写了这个示例程序。

# main.py

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

########################################################################
class KVMyHBoxLayout(BoxLayout):
    pass


########################################################################
class ExampleApp(App):
    def Pressbtn(self, *args):
        print'Pressed button'
    #----------------------------------------------------------------------
    def build(self):

        return KVMyHBoxLayout()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = ExampleApp()
    app.run()

kv file

<MyButton@Button>:
    color: .8,.9,0,1
    font_size: 32

<KVMyHBoxLayout>:
    orientation: 'vertical'
    MyButton:
        id:"idBtn1"
        text: "Btn1"
        background_color: 1,0,0,1
        on_press:app.Pressbtn()
    MyButton:
        id:"idBtn2"
        text: "Btn2"
        background_color: 0,1,0,1
        on_press:app.Pressbtn()
    Label:
        text: "ID"
        background_color: 0,0,1,1
    Label:
        text: "Text"
        background_color: 1,0,1,1

当按下按钮时,其相应的 id 和 text 值将显示在 ID 和 Text 标签中。目前以上代码仅打印按下按钮当按钮被按下时。我想知道如何以Python方式获取按钮的id和文本值。


首先,当从 kv 调用该方法时,必须将按钮实例显式传递给该方法:

on_press: app.Pressbtn(self)

然后您可以使用实例引用来修改按钮或查看其属性,您不需要id。如果您想获得id,你只能使用ids按钮父级的字典。

基于您的代码的示例:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

kv_file = '''
<MyButton@Button>:
    color: .8,.9,0,1
    font_size: 32

<KVMyHBoxLayout>:
    orientation: 'vertical'
    MyButton:
        id:"idBtn1"
        text: "Btn1"
        background_color: 1,0,0,1
        on_press:app.Pressbtn(self)
    MyButton:
        id:"idBtn2"
        text: "Btn2"
        background_color: 0,1,0,1
        on_press:app.Pressbtn(self)
    Label:
        id: lobj
        text: "Object"
        background_color: 1,0,1,1

    Label:
        id: lid
        text: "ID"
        background_color: 0,0,1,1
    Label:
        id: ltext
        text: "Text"
        background_color: 1,0,1,1
'''


class KVMyHBoxLayout(BoxLayout):
    pass

class ExampleApp(App):
    def Pressbtn(self, instance):
        instance.parent.ids.lobj.text = str(instance)
        instance.parent.ids.ltext.text = instance.text
        instance.parent.ids.lid.text= self.get_id(instance)

    def get_id(self,  instance):
        for id, widget in instance.parent.ids.items():
            if widget.__self__ == instance:
                return id

    def build(self):
        Builder.load_string(kv_file)
        return KVMyHBoxLayout()

if __name__ == "__main__":
    app = ExampleApp()
    app.run()

Output:

enter image description here

Edit:

如果您在 .py 文件中定义小部件(按钮),则不需要将实例传递给函数,它会作为参数自动传递:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView


class FirstScreen(Screen):
    def __init__(self,**kwargs):
        super(FirstScreen, self).__init__(**kwargs)    
        layout=BoxLayout(orientation="vertical",size_hint_y= None)
        layout.bind(minimum_height=layout.setter('height'))                
        for i in range(50):
                btn = Button(text="Button"+str(i),
                             id=str(i),
                             size_hint=(None, None),
                             on_press=self.Press_auth)               #<<<<<<<<<<<<<<<<           
                layout.add_widget(btn)
        root = ScrollView()
        root.add_widget(layout)
        self.add_widget(root)

    def Press_auth(self,instance):     
        print(str(instance))

class TestScreenManager(ScreenManager):
    def __init__(self,  **kwargs):
        super(TestScreenManager,  self).__init__(**kwargs)
        self.add_widget(FirstScreen())

class ExampleApp(App):
    def build(self):           
        return TestScreenManager()

def main():
    app = ExampleApp()
    app.run()

if __name__ == '__main__':
    main()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取 kivy 按钮的 Id 和 Text 值作为字符串? 的相关文章

随机推荐