Juanvulcano
Juanvulcano

Reputation: 1396

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):
    global Tiles

.kv

<TreasureHuntGrid>:
cols: #Don't know what should I put in here

Upvotes: 1

Views: 2787

Answers (1)

Nykakin
Nykakin

Reputation: 8747

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

class MyWidget(GridLayout):
    pass

class MyApp(App):
    tiles = 5
    def build(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"
""")

class MyWidget(GridLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

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

Upvotes: 4

Related Questions