Skip to main content
 首页 » 编程设计

python之Kivy 访问 .kv 变量

2024年09月07日13tuyile006

我正在为 python 使用 Kivy,我想知道是否有一种方法可以像这样访问我在 .kv 文件中声明的一些变量:

#:set global_background_color_A (0.4,0.4,0.4, 1) 
#:set global_background_color_B (0.2,0.2,0.2, 1) 
#:set global_background_color_C (0.6,0.6,0.6, 1) 
#:set global_seperator_color_Blue (0.26,.545,.65,1) 

现在,如果我可以在我的 python 代码中动态更改某些按钮的背景颜色,那就太好了。为此,我必须访问这些变量。

这样做最简单的方法是什么?

提前致谢, 芬恩

请您参考如下方法:

我使用以下代码作为示例应用程序:

controller.kv

#:kivy 1.0 
#:set global_background_color_A (0.4,0.4,0.4, 1) 
#:set global_background_color_B (0.2,0.2,0.2, 1) 
#:set global_background_color_C (0.6,0.6,0.6, 1) 
#:set global_seperator_color_Blue (0.26,.545,.65,1) 
 
<Controller>: 
    label_wid: my_custom_label 
    button_wid: my_custom_button 
 
    BoxLayout: 
        orientation: 'vertical' 
        padding: 20 
 
        Button: 
            id: my_custom_button 
            text: 'My controller info is: ' + root.info 
            on_press: root.do_action() 
 
        Label: 
            id: my_custom_label 
            text: 'My label before button press' 

__main__.py

import kivy 
kivy.require('1.0.5') 
 
from kivy.uix.floatlayout import FloatLayout 
from kivy.app import App 
from kivy.properties import ObjectProperty, StringProperty 
 
from kivy.lang.parser import global_idmap                   # <-- 
 
 
class Controller(FloatLayout): 
    '''Create a controller that receives a custom widget from the kv lang file. 
 
    Add an action to be called from the kv lang file. 
    ''' 
    label_wid = ObjectProperty() 
    info = StringProperty() 
 
    def do_action(self): 
        kv_var = global_idmap['global_background_color_A']  # <-- 
        self.label_wid.text = str(kv_var)                   # <-- 
        self.info = 'New info text' 
 
 
class ControllerApp(App): 
 
    def build(self): 
        return Controller(info='Hello world') 
 
 
if __name__ == '__main__': 
    ControllerApp().run() 

我用箭头标记了 __main__.py 中的重要行。

如果你看一下 kv 语言解析器 here ,您可以使用 set 命令查看它在做什么。它会进行一些错误检查,并且 eval() 是容器 global_idmap 中的值。

现在,我不认为这是值得推荐的。如你所见here , kivy 特别不公开 global_idmap。我想这是一个不应依赖的实现细节。

如果你想在代码中改变你的东西的颜色,你可以这样做:

def do_action(self): 
    ... 
    self.button_wid.background_color = (1, 0, 1, 1)