【问题标题】:bind, text of label in kv file to a method in python file将 kv 文件中的标签文本绑定到 python 文件中的方法
【发布时间】:2020-07-11 17:56:46
【问题描述】:

我想用简单的话将 .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 必须是字符串

【问题讨论】:

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


【解决方案1】:

您可以使用 kivy 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 文本。要对其进行测试,您可以使用 Appbuild() 方法作为:

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

【讨论】:

  • 你能再解释一下吗,因为我试过这个,它在我通过 StringProperty() 传递的屏幕上只显示“未设置”
  • 仔细看我的回答,并在你看到quote_text的地方记下。确保您的代码具有相同的更改。
  • 如果我在我的 mdapp 类中返回 main,那么我的样式就不会出现
  • 如果不查看更多代码,很难判断发生了什么。这就是为什么我们通常要求您发布minimal reproducible example
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
相关资源
最近更新 更多