Python Kivy,KV代码

时间:2017-07-29 18:10:53

标签: python oop kivy

您好,我无法找到答案的简单问题, 说我上课了:

class KivyApp(App):
    someVariable = "blahblah"

然后在KV代码中说我想放置文本,这是' someVariable' 我怎样才能做到这一点?我尝试过' KivyApp.someVariable',' app.someVariable' ' root.KivyApp.someVariable'等......以及其他排列。对基本问题感到遗憾,但我很难过。感谢任何答案。

1 个答案:

答案 0 :(得分:0)

这是有效的

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.properties import StringProperty



kv_str = Builder.load_string("""
Button:
    on_press: print(app.label_text)
""")

class MyApp(App):
    label_text = StringProperty()

    def __init__(self, **kwargs):
        self.label_text = 'Palim'
        super(MyApp, self).__init__(**kwargs)

    def build(self):
        return kv_str

if __name__ == '__main__':
    MyApp().run()

这不是

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.properties import StringProperty



kv_str = Builder.load_string("""
Button:
    text: app.label_text
    on_press: print(app.label_text)
""")

class MyApp(App):
    label_text = StringProperty()

    def __init__(self, **kwargs):
        self.label_text = 'Palim'
        super(MyApp, self).__init__(**kwargs)

    def build(self):
        return kv_str

if __name__ == '__main__':
    MyApp().run()

我相信kivy在初始化Button或你的案例标签上的文字时没有设置属性。

但一般情况下,我会将此文本贴在标签本身上。

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label


class Lbl(Label):

    def __init__(self, **kwargs):
        self.text = 'Palim'
        super(Lbl, self).__init__(**kwargs)


kv_str = Builder.load_string("""
Lbl:
""")

class MyApp(App):

    def build(self):
        return kv_str

if __name__ == '__main__':
    MyApp().run()