跳到内容

Kivy 入门教程/Hello World!

来自维基教科书,开放的书籍,为一个开放的世界

Hello World!

[编辑 | 编辑源代码]

在 Kivy 中,您需要做的第一件事是让一个屏幕出现。当您在 PC 上工作时,也会打开一个命令屏幕。如果您运行任何打印函数(我喜欢这些用于调试),它们将出现在命令屏幕中(我假设是 Apple OS 的终端,但我没有一个可以玩)。

打开 Python IDLE,然后打开一个新窗口以创建一个可保存的程序,并将以下代码复制到其中

代码示例 0
让一个屏幕出现
#!/usr/bin/env python 
from kivy.app import App #We need to import the bits of kivy we need as we need them as importing everything would slow the app down unnecessarily
from kivy.uix.widget import Widget #this is a thing that you want the App to display


class Lesson0(Widget): #this defines the instance of the widget. 
    pass # pass is used to keep the class valid but allow it not to contain anything - At the moment our widget is not defined.


class MyApp(App):
    def build(self):
        return Lesson0()

if __name__ == '__main__': #Documentation suggests that each program file should be called main.py but I think that only matters if you're creating the final App to go onto a phone or tablet we're a long way off from that yet

    MyApp().run() #This must match the name of your App

您需要通过 kivy 批处理文件运行它,才能让它与 kivy 库一起运行。有一种方法可以解决这个问题,但它可能很混乱,而这种方法效果很好。您可以在 kivy 网站上找到关于如何设置它的完整说明 这里。它应该打开一个空的黑色屏幕。

现在我们想要在屏幕上显示我们的“Hello World!”文本。为此,我们需要使用一个 Label 来显示文本。

代码示例 1
显示“Hello World!”
#!/usr/bin/env python 
from kivy.app import App #We need to import the bits of kivy we need as we need them as importing everything would slow the app down unnecessarily
from kivy.uix.widget import Widget #this is a thing that you want the App to display
from kivy.uix.label import Label #this will import the code for the label in which we want to display Hello World! 


class Lesson1App(App):
    def build(self):
        lbl=Label(text='Hello World!') #lbl is a variable name being assigned the Label definition
        return lbl #This  must match the name of the Widget you want to appear on screen

if __name__ == '__main__': #Documentation suggests that each program file should be called main.py but I think that only matters if you're creating the final App to go onto a phone or tablet we're a long way off from that yet

    Lesson1App().run() #This must match the name of your App
华夏公益教科书