跳到內容

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
華夏公益教科書