如何通过调用Kivy Python中的函数来设置小部件属性?

2024-07-08 11:11:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我在RootWidget中有一个ThemeManager对象作为类属性,如下所示:

class RootWidget(Widget):
    theme = ThemeManager()

ThemeManager定义了一个返回十六进制颜色的函数。在

^{pr2}$

假设我使用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()

Tags: 文件函数fromimportgetbuttonwidgettheme
1条回答
网友
1楼 · 发布于 2024-07-08 11:11:48

既然你的问题已经得到了回答,这里就来解释一下,其实很简单(我想)。在

在应用程序根目录在您的按钮尝试读取函数时为无。因为事情的顺序是(松散地):-

  1. RootWidget已创建
  2. 一旦它及其所有子对象完成(init完成),对象将被传递到build()中的行
  3. 在应用程序根目录只在调用时设置测试应用程序运行()

至于为什么3。发生时,init方法应用程序副本初始化自我.root因为没有。然后可以通过load_kv(加载与此应用程序同名的kv)或run(这是大多数情况下发生的情况)来设置它。在

所以你可以打电话应用程序根目录在你的on_press事件中(因为这些事件只发生在应用程序完全创建时的用户交互中),而不是一次性的widget初始化事件中。在

有趣的是,根在中没有定义为ObjectProperty应用程序副本,这意味着您不能像绑定标题和图标那样绑定到其中的更改。但不确定它是否会改变,所以这可能是没有意义的。在

相关问题 更多 >

    热门问题