【问题标题】:How to access a global var in Kivy file?如何访问 Kivy 文件中的全局变量?
【发布时间】:2015-12-13 19:15:22
【问题描述】:

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

main.py

Tiles = 5
class TreasureHuntGrid(GridLayout):
    global Tiles

.kv

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

【问题讨论】:

    标签: python-2.7 kivy


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-04
      • 2015-03-30
      • 2016-10-06
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多