Kivy For The Non Computer Scientist – Part 12 – KV Language – Switching Between Kivy GUI Screens

In this blog post we’ll build upon the code from Kivy For The Non Computer Scientist – Part 10: KV Language but we’ll stay from the blog material in Part 11 in order to provide working Kivy/Python code as as clean and as clear as possible. I trust those making use of code from these posts will use them as templates and use the various code bits as required for their specific application.

This blog post contains complete working code that demonstrates how to make Kivy buttons interactive by switching between four different screens. The welcome page will appear as follows and by reading the buttons it’s pretty clear what each button does;

gui

The complete and working code (with comments) for this Kivy screen switching app is as follows;

import kivy  # Required to run Kivy such as the next line of code
kivy.require('1.9.1')  # used to alert user if this code is run on an earlier version of Kivy.
from kivy.app import App  # Imports the base App class required for Kivy Apps
from kivy.lang import Builder  # Imports the KV language builder that provides the layout of kivy screens
from kivy.uix.screenmanager import ScreenManager, Screen # Imports the Kivy Screen manager and Kivys Screen class

Builder.load_string(""" # String that will build all four Kivy screens.
<WelcomeScreen>: # Identifies layout/interactivity for the WelcomeScreen.
    GridLayout: # Creates a GridLayout for WelcomeScreen.
        cols: 1 # Sets column property to 1.
        Label: # Creates a Label Widget instance.
            text: "You're On The Welcome Screen. Please Select Which Screen You Want To Go To" # Sets above Label text property
        Button: # Creates a Button Widget instance.
            text: 'Switch To Screen One' #  Sets above button text property
            on_release:
                # on_release is a Kivy mouse release event.
                root.manager.transition.direction = 'right' # Sets screen transition movement to right.
                root.manager.current = 'screen_one' # Switches Kivy GUI screen to screen one.
        Button: # Creates a Button Widget instance.
            text: 'Switch To Screen Two' #  Sets above button text property
            on_release:
                # on_release is a Kivy mouse release event.
                root.manager.transition.direction = 'right' # Sets screen transition movement to right.
                root.manager.current = 'screen_two' # Switches Kivy GUI screen to screen two.
        Button: # Creates a Button Widget instance.
            text: 'Switch To Screen Three' #  Sets above button text property
            on_release:
                # on_release is a Kivy mouse release event.
                root.manager.transition.direction = 'right' # Sets screen transition movement to right.
                root.manager.current = 'screen_three' # Switches Kivy GUI screen to screen three.
<FirstScreen>: # Identifies layout/interactivity for the FirstScreen.
    GridLayout: # Creates a GridLayout for FirstScreen.
        cols: 1 # Sets column property to 1.
        Button: # Creates a Button Widget instance.
            text: "You're On Screen One. Press To Return To Welcome Screen" #  Sets above button text property
            on_release:
                # on_release is a Kivy mouse release event.
                root.manager.transition.direction = 'right' # Sets screen transition movement to right.
                root.manager.current = 'welcome_screen' # Switches Kivy GUI screen to the welcome screen.
<SecondScreen>: # Identifies layout/interactivity for the SecondScreen.
    GridLayout: # Creates a GridLayout for SecondScreen.
        cols: 1 # Sets column property to 1.
        Button: # Creates a Button Widget instance.
            text: "You're On Screen Two. Press To Return To Welcome Screen" #  Sets above button text property
            on_release:
                # on_release is a Kivy mouse release event
                root.manager.transition.direction = 'right' # Sets screen transition movement to right.
                root.manager.current = 'welcome_screen' # Switches Kivy GUI screen to the welcome screen.
<ThirdScreen>: # Identifies layout/interactivity for the ThirdScreen.
    GridLayout: # Creates a GridLayout for ThirdScreen.
        cols: 1 # Sets column property to 1.
        Button: # Creates a Button Widget instance.
            text: "You're On Screen Three. Press To Return To Welcome Screen" #  Sets above button text property
            on_release:
                # on_release is a Kivy mouse release event
                root.manager.transition.direction = 'right' # Sets screen transition movement to right.
                root.manager.current = 'welcome_screen' # Switches Kivy GUI screen to the welcome screen.
""")

class WelcomeScreen(Screen): # Creates a WelcomeScreen widget from the above kv language data string.
    pass # Python placeholder for class.

class FirstScreen(Screen): # Creates a FirstScreen widget from the above kv language data string.
    pass # Python placeholder for class.

class SecondScreen(Screen): # Creates a SecondScreen widget from the above kv language data string.
    pass # Python placeholder for class.

class ThirdScreen(Screen): # Creates a ThirdScreen widget from the above kv language data string.
    pass # Python placeholder for class.

sm = ScreenManager() # Creates an instance (copy) of ScreenManager as variable sm. ScreenManager switches between Screen Objects.
sm.add_widget(WelcomeScreen(name='welcome_screen')) # Adds WelcomeScreen widget to ScreenManager. ScreenManager id's screen as welcome_screen.
sm.add_widget(FirstScreen(name='screen_one')) # Adds FirstScreen widget to ScreenManager. ScreenManager id's screen as screen_one.
sm.add_widget(SecondScreen(name='screen_two')) # Adds SecondScreen widget to ScreenManager. ScreenManager id's screen as screen_two.
sm.add_widget(ThirdScreen(name='screen_three')) # Adds ThirdScreen widget to ScreenManager. ScreenManager id's screen as screen_three.

class SwitchingScreenApp(App):  # Creates the instance (copy) of the Kivy App class named SwitchingScreenApp

    def build(self):  # build is a method of Kivy's App class used to place widgets onto the GUI.
        return sm  # return calls the build method which in turn builds the GUI.

SwitchingScreenApp().run() # Runs SwitchingScreenApp

So what’s new in the above code?

  • Line 5  – Imports Kivy’s ScreenManager and Kivy’s Screen class. ScreenManager is used later in the code to switch between screen objects. In order for ScreenManager to work Kivy Screens must be turned into screen objects. This is done later in the code.
  • Line 8 – Notice that is enclosed in braces. This indicates to Kivy that all the code indented below it is a set of rules that apply to a class. Since will eventually become a Screen object that will switched by ScreenManager,  the braces act as a demarkation point for each screen in kv language.
  • Line 15 – on_release is a kv language event call. In this case it occurs upon the release of a mouse click.
  • Line 17 – Makes up the first part of the event. In this case the event (root.manager.transition.direction = ‘right’) instructs the ScreenManager to change the screen it a right handed direction.
  • Line 18 – Makes up the second part of the event. In this case

    (root.manager.current = ‘screen_one’) tells the ScreenManager to switch screens to screen_one. Please note ScreenManager does not switch on its object name (FirstScreen). This confused me for some time when I first tried coding Kivy’s screen switching.

  • Lines 21, 23, 24, 27, 29 and 30 – Provides the same code and functions as Lines 15, 17 and 18 but this time for the second and third buttons on the WelcomeScreen. Note Line 24 switches Kivy’s GUI screen to screen_two and Line 30 switches Kivy’s GUI screen to ‘screen_three’.
  • Line 31 – Demarkation point for rules, layout, interactivity etc.
  • Line 39 – Event code calls for Kivy’s GUI screen to switch from ‘screen_one’ back to ‘welcome_screen’
  • Line 40 – Demarkation point for <SecondScreen> rules, layout, interactivity etc.
  • Line 48 – Event code calls for Kivy’s GUI screen to switch from ‘screen_two’ back to ‘welcome_screen’
  • Line 49 – Demarkation point for <ThirdScreen> , layout, interactivity etc.
  • Line 57 – Event code calls for Kivy’s GUI screen to switch from ‘screen_three’ back to ‘welcome_screen’
  • Line 60 – This is the line where the WelcomeScreen rules in the kv language string are turned into a Screen Object called WelcomeScreen.
  • Line 63 – This is the line where the FirstScreen rules in the kv language string are turned into a Screen Object called FirstScreen.
  • Line 66 – This is the line where the SecondScreen rules in the kv language string are turned into a Screen Object called SecondScreen.
  • Line 69 – This is the line where the ThirdScreen rules in the kv language string are turned into a Screen Object called ThirdScreen.
  • Line 72 – Creates an instance (copy) of ScreenManager as variable sm. As state earlier ScreenManager is used to display and switch between Screen Objects.
  • Line 73 – The WelcomeScreen Object is added to the ScreenManager and given the name ‘welcome_screen’. Note ScreenManager uses the name welcome_screen to perform any switches. It does not use the Object name WelcomeScreen.
  • Line 74 – The FirstScreen Object is added to the ScreenManager and given the name ‘screen_one’. Note ScreenManager uses the name screen_one to perform any switches. It does not use the Object name FirstScreen.
  • Line 75 – The SecondScreen Object is added to the ScreenManager and given the name ‘screen_two’. Note ScreenManager uses the name screen_two to perform any switches. It does not use the Object name SecondScreen.
  • Line 76 – The ThirdScreen Object is added to the ScreenManager and given the name ‘screen_three’. Note ScreenManager uses the name screen_three to perform any switches. It does not use the Object name ThirdScreen.

This is where I will wrap up this blog post. You can find more on Kivy’s ScreenManager at http://bit.ly/2ilJNEf. If nothing else the code in this post will get you started in developing a Kivy GUI with multiple screens and the ability to switch between them. In future posts we’ll need to take a look at nested screens and further Kivy interaction with Python. Kivy For The Non Computer Scientist – Part 13: Creating More Complex Kivy GUI’s Using Nesting And KV Language is the next post in this series.

….brad….

Kivy For The Non Computer Scientist – Part 11: Using KV Language To Set Widget Text Size, Text Position And Text And Button Colours

Before continuing on to adding interactivity to this Kivy GUI, this blog post will look at how one can customize a buttons text size, text position text colour and button colour using the KV Language.

To give you an idea this post will build on the code from Kivy For The Non Computer Scientist – Part 10: KV Language and the Kivy Gui will build as follows;

buttons

The code for this Kivy GUI (with line comments) is as follows;
import kivy  # Required to run Kivy such as the next line of code

kivy.require('1.9.1')  # used to alert user if this code is run on an earlier version of Kivy.
from kivy.app import App  # Imports the base App class required for Kivy Apps
from kivy.lang import Builder  # Imports the KV language builder that provides the layout of kivy screens

kivyscreen = Builder.load_string(""" # The variable kivyscreen is assigned the string that will build Kivy screens
GridLayout: # Creates a GridLayout for use in the app.
    cols: 1 # Sets column property to 1

    Label: # Creates a Label Widget instance.
        text: "I'm A Label With Black Text And Green Background" # Sets above Label text property
        color: 0,0,0,1 # Sets text colour to black.
        canvas.before:
            Color:
                rgba: 0, 1, 1, 1 # Sets widget canvas towards green
            Rectangle:
                pos: self.pos # required to position rectangle inside of Label widget.
                size: self.size # required to position rectangle inside of Label widget.

    Button: # Creates a Button Widget instance.
        text: "I'm Button 1 And I Have Purple Text" #  Sets above button text property to I'm Button 1
        color: 1,0,1,1 # Sets colour for button text

    Button: # Creates a Button Widget instance.
        text: "I'm Button 2 And I Have A Blue Background" #  Sets above button text property to I'm Button 2
        background_normal: "" # Button background defalts to grey. This sets the background to plain.
        background_color: (0.0, 0.0, 1.0, 1.0)# Sets the buttons colour to blue.

    Button: # Creates a Button Widget instance.
        text: "I'm Button 3 And I Have A Larger Text Size" #  Sets above button text property to I'm Button 3
        font_size: '25sp' # Changes default text size

    Button: # Creates a Button Widget instance.
        text: "I'm Button 4 And I'm Aligned Right" #  Sets above button text property to I'm Button 5
        text_size: self.size # constrains text to button size
        halign: 'right' # Sets text horizontal alignment to right side of button.
        valign: 'middle' # Sets text vertical alignment to centre of button.

    Button: # Creates a Button Widget instance.
        text: "I'm Button 5. I Have A Larger Text Size. And My Text Wraps.... See.....See.....See.....See..... See.....See.....See.....See....." #  Sets above button text property to I'm Button 4
        text_size: self.size # constrains text to button size
        font_size: '25sp' # Changes default text size
        halign: 'center' # Sets text horizontal alignment to cenre of button.
        valign: 'middle' # Sets text vertical alignment to centre of button.
""")

class FiveButtonApp(App):  # Creates the instance (copy) of the Kivy App class named FiveButtonApp.
    def build(self):  # build is a method of Kivy's App class used to place widgets onto the GUI.
        return kivyscreen  # return calls the build method which in turn builds the GUI.

FiveButtonApp().run()

By now most of the code and line by line comments should speak for itself in terms of alignment. I could not find all of the information on how to do these kinds of alignments in any one place. What’s striking is how different the code is depending on the widget especially relating to colour. There are two principles that I came across while putting together this blog post on Kivy that one has to wrap their head around while applying code. They are;

Hope this information helps you with your Kivy GUI designs. Here’s the link to the next post in this series, Kivy For The Non Computer Scientist – Part 12 – KV Language – Switching Between Kivy GUI Screens.

….brad….

Kivy For The Non Computer Scientist – Part 10: KV Language

To this point in this blog series all of the code and Kivy layout has been done using pure python and in a manner familiar to python programmers. In this first post of this blog series I indicated that Kivy has something called KV Language.

Kivy Language is:

  • a different language from Python
  • is something akin to what CSS does for HTML
    • it’s great for screen layouts
      • it adds widgets, screen layouts, defines widget properties etc.
  • it can be loaded into your app in one of two ways
    • from a separate file
    • as a string that’s part of your Python code file

Kivy Language is not:

  • something that you manipulate directly
    • KV Language provides your initial screen layout, various widgets, buttons and labels.
    • Python is used to manipulate buttons, labels, and widget properties.
      • much like Javascript manipulates CSS in HTML web pages.

In this post we are going to create a five button kivy screen using KV Language. It will look as follows;

five_button

The complete code to accomplish this with comments is as follows;

import kivy # Required to run Kivy such as the next line of code
kivy.require('1.9.1') # used to alert user if this code is run on an earlier version of Kivy.
from kivy.app import App # Imports the base App class required for Kivy Apps
from kivy.lang import Builder # Imports the KV language builder that provides the layout of kivy screens

kivyscreen = Builder.load_string(""" # The variable kivyscreen is assigned the string that will build Kivy screens
GridLayout: # Creates a GridLayout for use in the app.
    cols: 1 # Sets column property to 1

    Button: # Creates a Button Widget instance.
        text: "I'm Button 1" #  Sets above button text property to I'm Button 1

    Button: # Creates a Button Widget instance.
        text: "I'm Button 2" #  Sets above button text property to I'm Button 2

    Button: # Creates a Button Widget instance.
        text: "I'm Button 3" #  Sets above button text property to I'm Button 3

    Button: # Creates a Button Widget instance.
        text: "I'm Button 4" #  Sets above button text property to I'm Button 4

    Button: # Creates a Button Widget instance.
        text: "I'm Button 5" #  Sets above button text property to I'm Button 5
""") # End of string.

class FiveButtonApp(App): # Creates the instance (copy) of the Kivy App class named FiveButtonApp.
    def build(self): # build is a method of Kivy's App class used to place widgets onto the GUI.
        return kivyscreen # return calls the build method which in turn builds the GUI.

FiveButtonApp().run()  # Calls the FiveButtonApp object to run the app.

New in the code is as follows;

  • Line 6 thru 24 – The variable kivyscreen is assigned the string that will build Kivy screens. Builder.load_string is connected to Kivy’s build that that places screen widgets (in this case the five buttons) on the GUI when called.
  • Line 28 – kivyscreen is called from this line.

One great thing about using the kv language is how much less code is required to create and place the widgets onto a Kivy GUI. In our next few posts we’ll look at how to add events that will provide the interactivity for this viewer. Here’s the link to Kivy For The Non Computer Scientist – Part 11: Using KV Language To Set Widget Text Size, Text Position And Text And Button Colours

….brad….

A rare glimpse into the Antarctic underwater world….

The Effects Of AI On Lip Reading Sentences in the Wild

What happens to abandoned oil and gas wells in Texas?

Kivy Showcase: a short exploration of how Kivy is changing the world