将变量从.py文件传递到.kv文件

时间:2015-11-04 14:27:13

标签: python kivy

我是Kivy的新手,我在工作中学习。我对如何利用各种小部件和嵌套布局有了基本的了解。代码如下(保存为GUI.py): -

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.properties import ListProperty, NumericProperty, StringProperty

class TestScreen(Screen):
    pass

class VariableScreen(Screen):
    pass

class SummaryScreen(Screen):
    pass

class ProgressScreen(Screen):
    pass

class CompletedResultsScreen(Screen):
    pass

class SavedResultsScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

GUI_code = Builder.load_file("GUI.kv")

class GUIWindow(App):        #App class is inherited
    sampletext = StringProperty("Five times Five")

    def build(self):
        return GUI_code

if __name__ == "__main__":
    GUIWindow().run()

GUI.kv文件包含以下内容:

#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    TestScreen:
    VariableScreen:
    SummaryScreen:
    ProgressScreen:
    CompletedResultsScreen:
    SavedResultsScreen:

<TestScreen>:
    name: "Test_Screen"
    FloatLayout:
        Label:
            text: "Test"
            size_hint: 0.1,0.1
            pos_hint: {"right":0.5,"top":1}
        Label:
            text: app.sampletext
            size_hint: 0.1,0.1
            pos_hint: {"right":0.1,"top":1}
        Button:
            on_release: app.root.current = "Saved_Results_Screen"
            text: "Saved Results"
            size_hint: 0.1,0.1
            pos_hint: {"left":1,"bottom":1}
            font_size: 15
        Button:
            on_release: app.root.current = "Variable_Screen"
            text: "Variable"
            size_hint: 0.1,0.1
            pos_hint: {"right":1,"bottom":1}
            font_size: 15

仅发布.kv文件的相关部分。某些字符串必须从.py文件传递到.kv文件。这个问题在以下链接中解决:

Pass variable value from main.py to .kv file

根据那里的建议,我使用StringProperty类将sampletext放在GUIWindow类中。 (还尝试了一个简单的字符串sampletext =“五次五次”。给出相同的错误)

当第二个标签下的text属性设置为text时,代码不会运行:app.sampletext(打开空格的应用程序窗口。它没有响应。需要重新加载python内核才能关闭它)

显示以下错误消息

 18: pos_hint: {"right":0.5,"top":1}
 19: Label:
 >>   20: text: app.sampletext
 21: size_hint: 0.1,0.1
 22: pos_hint: {"right":0.1,"top":1}
 ...
 AttributeError: 'NoneType' object has no attribute 'bind'

当text属性设置为text时,它正常运行:“Five five Five”

有人可以帮助解释出现了什么问题吗?

1 个答案:

答案 0 :(得分:1)

我找不到任何描述原因的文档,但是在解析文件时,解析器似乎正在尝试访问app.sampletext,而在App类被定义之前,您正在执行此操作更别说创造了。

Builder.parse行移到您的build(self):功能中,它会正常工作。