【问题标题】:How to bring a variable from the .py file to the .kv file?如何将 .py 文件中的变量带入 .kv 文件?
【发布时间】:2026-01-16 22:05:02
【问题描述】:

Kv 语言可以使用以下语法从其他文件中导入名称:

#:import name x.y.z

# The same as `from x.y import z as name` in Python code

但它没有提到如何从使用该 kv 语言的同一模块导入值。
假设我有以下代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.atlas import Atlas
from kivy.uix.button import Button

theme = Atlas('path/to/atlas')

Builder.load_string('''
<MyWidget>:
    background_normal: theme['widget_bg']
''')

class MyWidget(Button):
    pass

class TestApp(App):
    def build(self):
       return MyWidget() 

TestApp().run()

我想将theme Atlas 对象导入kv 代码以设置正确的背景。这怎么可能?

【问题讨论】:

  • 尝试在您的 .kv 文件中使用 root.theme 来使用该变量。
  • @GeorgeBou root 指的是当前的根小部件,我认为它与全局命名空间无关
  • 您也可以在小部件中传递全局变量...这不适合您吗?
  • @GeorgeBou 不,关键是让它全球化。我也想在 .py 代码的多个地方使用它

标签: python kivy kivy-language


【解决方案1】:

您可以将当前模块称为 __main__

#:import theme __main__.theme

<MyWidget>:
   background_normal: theme['widget_bg']

【讨论】: