Tuesday, May 27, 2014

7. Background Color

To add a background color to a Layout, you have to use canvas.




canvas refers to graphic instructions. The instructions could be non-visual such as setting a color and transformations, and are called context instructions. The other group of instructions involve actual objects like points and lines, and are called vertex instructions. All widgets can have a canvas.


# ex7.py

from kivy.uix.stacklayout import StackLayout
from kivy.app import App

class MyStack(StackLayout):
    pass
   
class Ex7App(App):
    def build(self):
        return MyStack()

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



First the color is set, giving a rgb value. Then, a filled rectangle is drawn, covering the entire Layout. This will form the background color.




In the kv file, a new rule is created. A new class is created called My Button and it inherits the properties of Button. The only value it changes is the color. Now, all buttons will have that color, for the text, provided that all references to Button are changed to My Button.




In the kv file, there are a total of 5 buttons. All of them are changed to My Button. There are also 2 Widgets which only act as placeholders of specific size. Note, here the 'B3' button is given a width of 100 pixels. The rule is that size_hint has to have a None in the x-value, if with width is fixed. This is because size_hint has precedence.


# ex7.kv

<MyButton@Button>:
    color: [0, 1, 1, 1]
    
<MyStack>:
    orientation: 'bt-rl'
    spacing: 20
    padding: [20,10]
    canvas:
        Color:
            rgb: [.5, .5, .95]
        Rectangle:
            pos: self.pos
            size: self.size
    MyButton:
        text: 'B1'
        size_hint: [.3,.4]
    MyButton:
        text: 'B2'
        size_hint: [.3,.4]
    Widget:
        size_hint: [None, .2]
        width: 100
    MyButton:
        text: 'B3'
        size_hint: [None,.4]
        width: 100
    Widget:
        size_hint: [None,.2]
        width: 100
    MyButton:
        text: 'B4'
        size_hint: [.3, .4]
    MyButton:
        text: 'B5'
        size_hint: [.3, .4]                   



This shows the result. There are empty spaces, which are occupied by the Widgets. If we did not add a Widget, after button B2, in the kv file, then the button will start at y of 0. However this particular Widget adds a relative y-spacing of 20%.




4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Python Training in electronic city

    ReplyDelete