user13080049
user13080049

Reputation:

How to refer to pos and size of widget in python canvas (KIVY)?

Here is what I do now, I create a function that can dynamically create a button (in boxlayout):

def create_class_button(self, size_hint_x:float, text:str, text_color:tuple, background_color:tuple) -> TextBoxLayout:
    # Ignore this box
    box = TextBoxLayout(size_hint_x=size_hint_x, padding=(30,6.5), on_press=self.list_item_pressed, background_color=(0,0,0,0))
    # RoundedButton inherited from Button
    btn = RoundedButton(text=text, on_press=self.list_item_pressed, color=text_color, background_color = (0,0,0,0))
    with btn.canvas.before:
            Color(rgba=background_color)
            Rectangle(size=btn.size, pos=btn.pos)
    box.add_widget(btn)
    return box

The canvas always draw at the point (0, 0).

How can I let it follow my RoundedButton position and size?

Upvotes: 0

Views: 522

Answers (1)

John Anderson
John Anderson

Reputation: 38837

After reading your question several time, I think you are asking how to get the Rectangle to follow your RoundedButton. The best way to do that is to create a rule in kv for the RoundedButton:

<RoundedButton>:
    canvas.before:
        Color:
            rgba: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size

You can do the same in python, but then you must set up bindings to get the Rectangle to follow the RoundedButton. The kv language sets up those bindings for you.

Also, note that the pos and size of a Widget initially get set to the defaults of (0,0) and (100,100), and they get updated when the Widget is drawn. So your canvas is using those initial defaults. And since no bindings are set up, the canvas does not change when the pos and size of the Widget change.

Upvotes: 0

Related Questions