如何在main.py中捆绑Kivy代码

时间:2017-01-11 15:06:50

标签: python kivy

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

2 个答案:

答案 0 :(得分:1)

你可以像这样在嵌入你的 .kv文件

Builder.load_string("""
<MyWidget>:
    ...

""")

class MyApp(App):
    ...

了解更多信息,请点击here

答案 1 :(得分: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()