[英]Python kivy get labels from *.py file in kivy file
I am trying to get labels from a python file (labels.py) and inject these labels into a label inside of a kivy file (pong.kv). 我正在尝试从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()
This is the labels.py file: 这是labels.py文件:
# labels.py
WORLD = "World"
And this is the kv file: 这是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
If I run the main.py file I get an error "NameError: name 'WORLD' is not defined". 如果我运行main.py文件,则会收到错误消息“ NameError:未定义名称'WORLD'”。 Replacing WORLD by "World" runs without any problems. 用“世界”代替WORLD毫无问题。
Assuming you do not have the 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 , so your import into .kv: 假设您没有安装pygame库 (如果安装了pygame库,则导入时会发生冲突),根据docs导入到.kv会遵循相同的python规则,因此,导入.kv的方法是:
#: import labels pygame.labels
it would translate into python in the following way: 它将以以下方式转换为python:
from pygame.labels as labels
So, keeping in mind the above, the way to obtain "WORLD" is using the namespace, that is, labels.WORLD
. 因此,请记住上述内容,获取“ WORLD”的方法是使用名称空间,即labels.WORLD
。 Consequently the .kv should be the following: 因此,.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.