将kv文件中的标签文本绑定到python文件中的方法

时间:2020-03-31 08:25:54

标签: python-3.x text label kivy kivy-language

我想用简单的词将.kv文件中的函数绑定到.py文件中的方法,我想每天在应用程序的主屏幕上更新引号,因此我使用屏幕小部件显示引号,所以我该怎么办?将label.text绑定到.py文件中的方法 这是我要绑定的.py文件的类

class MainScreen(FloatLayout):
    def quote(self):
        self.quote.text = 'I often think that the night is more alive and more richly colored than 
                             the day. - Vincent van Gogh'

这是.kv文件的根窗口小部件

    <MainScreen>:
        story: story

        canvas:
            Color:
                rgba: 0, 0, 0, 1
            Rectangle:
                pos: self.pos
                size: self.size

        Label:
            id: story
            text: root.quote
            font_size: '20sp'
            size: self.texture_size
            pos_hint: {'x': -0.2, 'y': 0.27}

但显示错误消息,提示label.text必须为字符串

1 个答案:

答案 0 :(得分:0)

您可以使用奇异的Property并使用quote()方法来更新Property。这是在代码中执行此操作的方法:

class MainScreen(FloatLayout):
    quote_text = StringProperty('Not Set')

    def quote(self, *args):
        self.quote_text = 'I often think that the night is more alive and more richly colored than  the day. - Vincent van Gogh'

quote_text是可以在StringProperty中引用的kv,并且quote方法现在更新了StringProperty

在您的kv中:

<MainScreen>:
    story: story

    canvas:
        Color:
            rgba: 0, 0, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

    Label:
        id: story
        text: root.quote_text
        font_size: '20sp'
        size: self.texture_size
        pos_hint: {'x': -0.2, 'y': 0.27}

然后,调用quote()方法将更新Label文本。要对其进行测试,可以使用build()中的App方法:

def build(self):
    main = MainScreen()
    Clock.schedule_once(main.quote, 5)
    return main
相关问题