Skip to main content
 首页 » 编程设计

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

2025年02月15日7jpfss

我正在学习 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() 

下载 appscreenmanager.kv

#:kivy 1.10.0 
 
<AppScreenManager>: 
    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' 

slider View .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() 

请您参考如下方法:

仅当您调用基类的 __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!