Python kivy 从 kivy 文件中的 *.py 文件获取标签
Python kivy get labels from *.py file in kivy file
我正在尝试从 python 文件 (labels.py) 获取标签并将这些标签注入到 kivy 文件 (pong.kv) 内的标签中。
# main.py
from kivy.app import App
from kivy.uix.widget import Widget
class PongGame(Widget):
pass
class PongApp(App):
def build(self):
return PongGame()
if __name__ == "__main__":
PongApp().run()
这是 labels.py 文件:
# labels.py
WORLD = "World"
这是 kv 文件:
#: kivy 1.10.1
#: import labels pygame.labels
<PongGame>:
canvas:
Rectangle:
pos: self.center_x - 5, 0
size: 10, self.height
Label:
font_size: 70
center_x: root.width / 4
top: root.top - 50
text: WORLD
如果我 运行 main.py 文件,我会得到一个错误 "NameError: name 'WORLD' is not defined"。将 WORLD 替换为 "World" 运行s 没有任何问题。
假设您没有 pygame library installed (if you have the pygame library installed you will have a conflict in the import), the import into .kv complies with the same python rules according the docs,那么您导入 .kv:
#: import labels pygame.labels
它将按以下方式转换为 python:
from pygame.labels as labels
所以,牢记以上,获取"WORLD"的方法是使用命名空间,即labels.WORLD
。因此 .kv 应如下所示:
#: kivy 1.10.1
#: import labels pygame.labels
<PongGame>:
canvas:
Rectangle:
pos: self.center_x - 5, 0
size: 10, self.height
Label:
font_size: 70
center_x: root.width / 4
top: root.top - 50
text: labels.WORLD
我正在尝试从 python 文件 (labels.py) 获取标签并将这些标签注入到 kivy 文件 (pong.kv) 内的标签中。
# main.py
from kivy.app import App
from kivy.uix.widget import Widget
class PongGame(Widget):
pass
class PongApp(App):
def build(self):
return PongGame()
if __name__ == "__main__":
PongApp().run()
这是 labels.py 文件:
# labels.py
WORLD = "World"
这是 kv 文件:
#: kivy 1.10.1
#: import labels pygame.labels
<PongGame>:
canvas:
Rectangle:
pos: self.center_x - 5, 0
size: 10, self.height
Label:
font_size: 70
center_x: root.width / 4
top: root.top - 50
text: WORLD
如果我 运行 main.py 文件,我会得到一个错误 "NameError: name 'WORLD' is not defined"。将 WORLD 替换为 "World" 运行s 没有任何问题。
假设您没有 pygame library installed (if you have the pygame library installed you will have a conflict in the import), the import into .kv complies with the same python rules according the docs,那么您导入 .kv:
#: import labels pygame.labels
它将按以下方式转换为 python:
from pygame.labels as labels
所以,牢记以上,获取"WORLD"的方法是使用命名空间,即labels.WORLD
。因此 .kv 应如下所示:
#: kivy 1.10.1
#: import labels pygame.labels
<PongGame>:
canvas:
Rectangle:
pos: self.center_x - 5, 0
size: 10, self.height
Label:
font_size: 70
center_x: root.width / 4
top: root.top - 50
text: labels.WORLD