【问题标题】:Trouble connecting objects in .kv file to python class将 .kv 文件中的对象连接到 python 类时出现问题
【发布时间】:2017-08-15 19:01:44
【问题描述】:

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

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

该应用程序可以很好地加载所有 kivy 文件,并且仅在我尝试从 Class 更新时才会中断。

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

主应用入口

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:
    ...

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()

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案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!
    

    【讨论】:

    • 我也试过了,得到了同样的结果。这让我觉得问题出在我的设置中的其他地方
    • 经过更多故障排除后,我只能在 init 方法中无法访问我的小部件。就好像它们还没有被创建。任何想法为什么会这样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2021-03-13
    • 1970-01-01
    • 2020-05-12
    • 2014-09-12
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多