无法将.kv文件中的对象连接到python类

时间:2017-08-15 19:01:45

标签: python kivy kivy-language

我正在学习Kivy并且无法将.kv文件中声明的对象连接到python类以更新其属性。无论我尝试哪种方式,我都会收到此错误:

self.kbCompressionLabel.text = 'Hello World'
AttributeError: 'NoneType' object has no attribute 'text'

该应用程序可以正常加载所有kivy文件,并且只有在我尝试从类更新时才会中断。

我已将目前的代码缩减到最低限度,以说明它是如何设置的。任何帮助深表感谢。

主要应用条目

import kivy
kivy.require('1.10.0')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager

Builder.load_file('appscreenmanager.kv')
Builder.load_file('compressorscreen.kv')
Builder.load_file('slidersview.kv')

class AppScreenManager(ScreenManager):
    pass

class AppManager(App):
    def build(self):
        return AppScreenManager()

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

Dumed down appscreenmanager.kv

#:kivy 1.10.0

<AppScreenManager>:
    CompressorScreen:
    ...

compressorscreen.kv

<CompressorScreen>:
    name: 'compressor'
    GridLayout:
        rows: 4
        cols: 1
    SlidersView:
    ...

这就是问题所在:简化的slidersview.kv

#:kivy 1.10.0
#:import slidersview slidersview

<slidersView>:
    cols: 4
    rows: 2
    id: sliders
    kbCompressionLabel: kbCompressionLabel

    Label:
        id: kbCompressionLabel
        text: 'test'

slidersview.py

import kivy
kivy.require('1.10.0')

from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class SlidersView(GridLayout):
    # properties
    sliders = ObjectProperty(None)
    kbCompressionLabel = ObjectProperty(None)

    def __init__(self, **kwargs):
        self.kbCompressionLabel.text = 'Hello World'
        super(SlidersView, self).__init__(**kwargs)

更新

我不得不在init函数中添加一个延迟然后工作。然而,这对我来说非常不稳定。这是预期的行为吗?

更新了slidersview.py

import kivy
kivy.require('1.10.0')

from kivy.clock import mainthread
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class SlidersView(GridLayout):
    # properties
    kbCompressionLabel = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(SlidersView, self).__init__(**kwargs)
        @mainthread
        def delayed():
            self.kbCompressionLabel.text = 'Hello World'
        delayed()

1 个答案:

答案 0 :(得分:1)

仅当您调用基类的__init__时才会应用KV定义... 扭转秩序,你会没事的......

class SlidersView(GridLayout):
    # properties
    sliders = ObjectProperty(None)
    kbCompressionLabel = ObjectProperty(None)

    def __init__(self, **kwargs):

        super(SlidersView, self).__init__(**kwargs) #first!
        self.kbCompressionLabel.text = 'Hello World' #2nd!