Before moving on I’d be remiss if I didn’t create a short post and update the code from Part 5 of this blog post series to make it more Pythonic and to conform to Kivy convention(s). Here is the updated code;
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.uix.gridlayout import GridLayout # imports the GridLayout class for use in the app. from kivy.uix.label import Label # Imports the Label Screen Widget for use in the app. from kivy.uix.button import Button # Imports the Button Screen Widget for use in the app. class TwoColumnApp(App): # Creates the instance (copy) of the Kivy App class named TwoColumnApp. def build(self): # build is a method of Kivy's App class used to place widgets onto the GUI. my_layout = GridLayout(cols = 2) # Sets grid layout and the number of columns to my_layout as the instance is created. One less line of code. self.my_first_button = Button(text="I'm A Button. Press Me", on_press = self.hello_world) # Creates a Button Widget instance and sets its text property to I'm A Button. Press Me. self.my_first_label = Label(text="Please Press My Button") # Creates a Label Widget instance and sets its text property to Please Press My Button. my_layout.add_widget(self.my_first_button) # Adds the button widget to my_layout my_layout.add_widget(self.my_first_label) # Adds the label widget to My_layout return my_layout # return calls the build method which in turn builds the GUI. def hello_world(self,event): # Creates the hello_world function to be used by button as its event. self.my_first_label.text = "Hello, world!" # Sets the GUIs label text property to Hello, world! when function is called. TwoColumnApp().run() # Calls the TwoColumnApp object to run the app.
Line 1 – Up to this point in our code creation we have only used widgets associated with Kivy’s App class. However in order to use other elements of Kivy, such as .kv language or in this case Kivy’s version requirement method on Line 2, one starts with the import kivy statement kivy because it loads Kivy’s framework.
Line 2 is code that uses Kivy’s framework to check the minimum version required to run this Kivy application. The programmer sets it to the Kivy version on which the code is written. If a user attempts to run your application with a version of Kivy that is older than the specified version, an Exception is raised.
Line 9 concatenates what was two lines of code into one by setting my_layout’s column count by setting it using GridLayout’s brackets.
Next In The Series
Since the learning goal of this series was to build a button, switch and checkbox interface, the next blog post will focus on the checkbox.
Next post in this blog series: Kivy For The Non Computer Scientist – Part 7: Simple Checkbox Code