Skip to content Skip to sidebar Skip to footer

How To Access A Global Var In Kivy File?

I have a global variable called Tiles and want to set the number of cols in the TreasureHuntGrid class to the kivy file. Main.py Tiles = 5 class TreasureHuntGrid(GridLayout):

Solution 1:

Globals are evil. If you want to have a variable accessible from any widget it's better to put it into the Application class, since you will only have one instance in your program:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder

Builder.load_string("""
<MyWidget>:
    cols: app.tiles
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
""")

classMyWidget(GridLayout):
    passclassMyApp(App):
    tiles = 5defbuild(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

Having said that, you can access global variables like this if you really need that:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder

tiles = 5

Builder.load_string("""
#: import tiles __main__.tiles

<MyWidget>:
    cols: tiles
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
""")

classMyWidget(GridLayout):
    passclassMyApp(App):
    defbuild(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

Post a Comment for "How To Access A Global Var In Kivy File?"