如何在Kivy文件中访问全局变量?

时间:2015-12-13 19:15:22

标签: python-2.7 kivy

我有一个名为Tiles的全局变量,并希望将TreasureHuntGrid类中的cols数设置为kivy文件。

Main.py

Tiles = 5
class TreasureHuntGrid(GridLayout):
    global Tiles

.kv

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

1 个答案:

答案 0 :(得分:4)

Globals are evil。如果您希望从任何窗口小部件访问变量,最好将其放入Application类,因为您的程序中只有一个实例:

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

话虽如此,如果您真的需要,可以访问这样的全局变量:

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