Getting Started With Kivy Tutorial/Hello World!

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Hello World![edit | edit source]

The first thing you need to do in Kivy is to make a screen appear. While you're working on a PC a command screen will open as well. If you run any print functions (I love those for debugging) they will appear in the command screen (I presume terminal for Apple OS but I don't have one to play with).

Open Python IDLE, then open a new window to create a savable program and copy in the following code:

Code Example 0
Make a screen appear
#!/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

You need to run this through the kivy batch file in order to get it to run with the kivy library. There is a way around this but it can be confusing and this works pretty well. You can find the full instructions of how to set this up on the kivy website here. It should open an empty black screen.

Now we want to display our "Hello World!" text on the screen. In order to do this we need to use a Label to display text.

Code Example 1
Show "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