如何从初始化的变量设置标签中的文本?

2024-09-29 23:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的t.py

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


class Simple(BoxLayout):
    def __init__(self, **kwargs):
        super(Simple, self).__init__(**kwargs)

        # THIS IS SIMLE EXAMPLE, IN PRACTICE I AM READING VALUE FROM TEXT FILE
        self.sometext = 'Hello from Init.'

    def set_text(self):
        return self.sometext # error: 'Simple' object has no attribute 'sometext'
        #return "Hello World from Simple(BoxLayout)" # this is working 


class TApp(App): 
    def build(self):
        return Simple()


TApp().run()

我的t.kv

^{pr2}$

所以这没用 需要做些什么才能让它工作?在

我希望这是可能的。。。在

谢谢


Tags: fromimportselfapphelloreturninitdef
1条回答
网友
1楼 · 发布于 2024-09-29 23:16:20

以下是我在kivy邮件列表中的回复:

It looks like the kv language ends up calling set_text before __init__, which seems weird but does explain your problem.

You could fix it in various ways, but I would do the whole thing using a kivy property to keep things simple. I made an example at https://gist.github.com/inclement/8268019 . Although the default is set to '', the kv lang can automatically detect that it's a property and make a binding so that when __init__ changes it the text is updated.

链接的示例代码是:

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

Builder.load_string('''
<Simple>:
    Label:
        #text: 'Hello World' # THIS IS WORKING
        text: root.sometext
''')

class Simple(BoxLayout):
    sometext = StringProperty('')

    def __init__(self, **kwargs):
        super(Simple, self).__init__(**kwargs)

        self.sometext = 'Hello from Init.'

class TApp(App):
    def build(self):
        return Simple()


TApp().run()

相关问题 更多 >

    热门问题