【问题标题】:How to bundle Kivy code in main.py如何在 main.py 中捆绑 Kivy 代码
【发布时间】:2017-01-15 16:18:37
【问题描述】:

我正在尝试构建一个 kivy 应用程序,我需要将我的 .py 文件和 .kv 文件放在一个名为 main.py 的文件中。我该怎么做呢?谢谢。

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    您需要为此使用 Builder。 Docs 下面的代码说明了这一点。

    from kivy.app import App
    from kivy.uix.gridlayout import GridLayout
    from kivy.lang import Builder
    
    Builder.load_string("""
    #:import hex kivy.utils.get_color_from_hex
    
    <Root>:
        cols: 2
        canvas:
            Color:
                rgba: 1, 1, 1, 1
            Rectangle:
                pos: self.pos
                size: self.size
    
        Label:
            canvas.before:
                Color:
                    rgb: 39/255., 174/255., 96/255.
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: "rgb: 39/255., 174/255., 96/255."
        Label:
            canvas.before:
                Color:
                    rgba: 39/255., 174/255., 96/255., 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: "rgba: 39/255., 174/255., 96/255., 1"
        Label:
            canvas.before:
                Color:
                    hsv: 145/360., 77.6/100, 68.2/100
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: "hsv: 145/360., 77.6/100, 68.2/100"
        Label:
            canvas.before:
                Color:
                    rgba: hex('#27ae60')
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: "rgba: hex('#27ae60')"
    """)
    
    
    class Root(GridLayout):
        pass
    
    
    class ColorusageApp(App):
        def build(self):
            return Root()
    
    
    if __name__ == "__main__":
         ColorusageApp().run() 
    

    【讨论】:

      【解决方案2】:

      您可以像这样嵌入您的 .kv 文件到 python 中

      Builder.load_string("""
      <MyWidget>:
          ...
      
      """)
      
      class MyApp(App):
          ...
      

      更多信息请点击here

      【讨论】:

        猜你喜欢
        • 2019-08-18
        • 1970-01-01
        • 2016-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多