1

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
Juanvulcano
  • 1,354
  • 3
  • 26
  • 44

1 Answers1

4

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()
Community
  • 1
  • 1
Nykakin
  • 8,657
  • 2
  • 29
  • 42