Google Analytics

Wednesday, May 7, 2014

Learning Kivy - Part 2


Table of Contents

  • Learning Kivy - Part 1
  • Learning Kivy - Part 2
  • Learning Kivy - Part 3
  • Learning Kivy - Part 4
  • Learning Kivy - Part 5
  • Learning Kivy - Part 6

    In our previous lesson, the Simple class extends App.  When the method is invoked, it will build the actual GUI screen.  But as you saw, at this point, that's an empty screen.

    The build method for Simple returned an instance of the Box_a class, which extended BoxLayout.

    If we put this Box_a class into the Kivy Language file simple.kv correctly, then we will have a GUI element, or widget, displayed.

    So, let's build the simple.kv file.  (Note: most articles I've seen have you instantiate a root window, but I'm not taking that approach.  See Dusty's articles for more insight on this topic.)

    I'm going to add two class definitions; Box_a and Simple.  These are coded in Kivy Language as:

    I'm putting two class definitions into this Kivy Language file, but with the current .py code, only the Box_a  will cause anything to be displayed; I'm putting the Simple class here to show that it doesn't get invoked.  Also, notice the indenting - it's the same required as Python; Kivy, afterall, is a GUI for Python.

    So, here's the complete simple.kv file:
            text: "Hello World from inside simple.kv, via Box_a"

            text: "Hello World from inside simple.kv, via Simple"

    If we now run our file, we will see a GUI with the contents of "Hello World from inside simple.kv, via Box_a"

    If you look at the output from the terminal window, you will still see the printouts "Box_a entry" and "inside build" text.

    Part of what I'm doing is learning the Kivy language.  And for me, that also means learning what it isn't; so I tend to play around with things to see what breaks.  The following is an example of what breaks, and why I tried it.

    Changing, the class method for build to return a reference to Simple.self instead of an instance of 'Box_a', causes the program to terminate.

    If you want to try this, in build, change the line
        return Box_a()
        return self

    It causes the GUI to flash onto and off the screen, and an error message:
    Attribute Error: 'Simple' ojbect has no attribute 'canvas'.

    I think my problem is with the fact that Simple extends App, instead of a Widget.

    So, you .run() the App class, but return a root widget.

    So, remove the useless <Simple>: class definition from the .kv file, as it won't ever be called!

    No comments:

    Post a Comment