KVLang Series – 6

KVLang Series – 6

← Previous                     

Class Rules

Content:

  • .kv file
  • .py file
  • screenshot of output

0006_classRules.kv

Class Rules allow you to make your own widget from previously defined widgets.
A Class Rule defines how any instance of that widget class will appear.
See:

<LblTxtBtn>:
    orientation: 'horizontal'

    Label:
        text: root.l_text
    TextInput:
        text: root.t_text
    Button:
        text: root.b_text


BoxLayout:
    orientation: 'vertical'    

    LblTxtBtn:
        l_text: 'init_lbl-1'
        t_text: 'init_text-1'
        b_text: 'init_btn-1'

    LblTxtBtn:
        l_text: 'init_lbl-2'
        t_text: 'init_text-2'
        b_text: 'init_btn-2'

    LblTxtBtn:
        l_text: 'init_lbl-3'
        t_text: 'init_text-3'
        b_text: 'init_btn-3'

0006_classRules.py

This is adapted from previous step. For Class Rules, as opposed to the upcoming Dynamic Classes, we need MAJOR ADDITIONS.
We need to ADD objects to allow us to use Class Rules and their properties in our .kv file.
Note how we need to look back and forth from the .kv file to the .py file to see what’s going on with the porperties.
This will NOT BE NECESSARY when we do the upcoming Dynamic Classes. Then the info will be contained in the .kv file.

  1. EDIT

    CHANGE: The OLD self.root = Builder.load_file(”) TO the NEW

  2. ADD – imports for LblTxtBtn classRule

    AFTER: from kivy.config import Config

    INSERT:

    from kivy.uix.boxlayout import BoxLayout

    from kivy.properties import StringProperty

  3. ADD – Class Code for LblTxtBtn classRule

    AFTER: Config.set(‘graphics’, ‘height’, ’90’)

    INSERT:

    class LblTxtBtn(BoxLayout):

    l_text = StringProperty('')
    
    t_text = StringProperty('')
    
    b_text = StringProperty('')    
    
''' 0006_classRules.py
Adds class LblTxtBtn(BoxLayout), etc. to display 0006_classRules.kv
'''

import kivy
kivy.require('1.8.0') # replace with your current kivy version !

from kivy.app import App
from kivy.lang import Builder
from kivy.config import Config

from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty 


Config.set('graphics', 'width',  '323')
Config.set('graphics', 'height', '90')

class LblTxtBtn(BoxLayout):

    l_text = StringProperty('')
    t_text = StringProperty('')
    b_text = StringProperty('')

class MyApp(App):

    def build(self):
        self.root = Builder.load_file('0006_classRules.kv')
        return self.root

if __name__ == '__main__':
    MyApp().run()

0006_classRules ScreenShot

Here is what this looks like run on Windows XP. In Pixels, it has:

  • width: 323
  • height: 200

Alt 0006_classRules.png

Advertisements