Mate
Mate

Reputation: 301

Canvas rectangle not moving with Label, why?

I am making gui app and i would like to randomly generate Labels with colored backgrounds for aesthetic reasons.

But whenever a Label is generated the Canvas Rectangle stays in the bottom left cornor.

pos_hint doesnt affect the Rectangle only the Label which text is moved where the pos_hint instructs it to.

Code:

import kivy
import random
from kivy.app import App
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button


class BackgroundLines(Label):
    def on_size(self, *args):
        self.canvas.before.clear()
        with self.canvas.before:
            Color(.2, .3, .4, 1)
            Rectangle(pos=self.pos, size=self.size)

class widget(FloatLayout):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        with self.canvas.before:
            Color(1, 1, 1, .5)
            Rectangle(pos=self.pos, size=self.size)

        n1 = random.randint(20, 65) / 100
        n2 = random.randint(20, 65) / 100
        b1 = Button(pos_hint={'x': 0, 'center_y': .5}, size_hint=(.3, .2))
        b2 = BackgroundLines(text='hidasd',size_hint=(.5, .2),pos_hint = {'x': n1, 'y': n2})

        self.add_widget(b1)
        self.add_widget(b2)


class TestApp(App):
    def build(self):
        return widget()


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

Upvotes: 0

Views: 41

Answers (1)

John Anderson
John Anderson

Reputation: 38937

The easiest way to accomplish what you want is to use kv. For example:

class BackgroundLines(Label):
    rgba = ListProperty([0.5, 0.5, 0.5, 1])

Builder.load_string('''
<BackgroundLines>:
    canvas.before:
        Color:
            rgba: self.rgba
        Rectangle:
            pos: self.pos
            size: self.size
''')

Then you can do:

b2 = BackgroundLines(text='hidasd',size_hint=(.5, .2),pos_hint = {'x': n1, 'y': n2}, rgba=[1, 0, 0, 1])

and:

b2.rgba = [0,0,1,1]

Upvotes: 2

Related Questions