假设我在RootWidget
中有一个ThemeManager
对象作为类属性,如下所示:
class RootWidget(Widget):
theme = ThemeManager()
ThemeManager
定义了一个返回十六进制颜色的函数。在
假设我使用kv
文件在RootWidget
中创建一个Button
。如何从kv
文件调用ThemeManager
函数?下面是一个不起作用的例子:
import kivy
kivy.require('1.9.0')
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.lang import Builder
class ThemeManager:
def get_color(self):
return '#ffffffff'
class RootWidget(Widget):
theme = ThemeManager()
my_kv = Builder.load_string("""
#: import get_color_from_hex kivy.utils.get_color_from_hex
RootWidget:
Button:
color: get_color_from_hex(app.root.theme.get_color())
text: "Test"
""")
class TestApp(App):
def build(self):
return my_kv
if __name__ == '__main__':
TestApp().run()
既然你的问题已经得到了回答,这里就来解释一下,其实很简单(我想)。在
在应用程序根目录在您的按钮尝试读取函数时为无。因为事情的顺序是(松散地):-
至于为什么3。发生时,init方法应用程序副本初始化自我.root因为没有。然后可以通过load_kv(加载与此应用程序同名的kv)或run(这是大多数情况下发生的情况)来设置它。在
所以你可以打电话应用程序根目录在你的on_press事件中(因为这些事件只发生在应用程序完全创建时的用户交互中),而不是一次性的widget初始化事件中。在
有趣的是,根在中没有定义为ObjectProperty应用程序副本,这意味着您不能像绑定标题和图标那样绑定到其中的更改。但不确定它是否会改变,所以这可能是没有意义的。在
相关问题 更多 >
编程相关推荐