如何将变量从 .py 文件带到 .kv 文件?

How to bring a variable from the .py file to the .kv file?

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 代码中以设置正确的背景。这怎么可能?

您可以将当前模块称为__main__

#:import theme __main__.theme

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