【发布时间】: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