简体   繁体   中英

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).

# 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
WORLD = "World"

And this is the kv file:

#: 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". Replacing WORLD by "World" runs without any problems.

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:

#: import labels pygame.labels

it would translate into python in the following way:

from pygame.labels as labels

So, keeping in mind the above, the way to obtain "WORLD" is using the namespace, that is, labels.WORLD . Consequently the .kv should be the following:

#: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM