如何在python画布(KIVY)中引用小部件的位置和大小?

2024-09-26 22:44:54 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我现在要做的,我创建了一个可以动态创建按钮的函数(在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

画布始终在点(0,0)处绘制

我如何让它跟随我的RoundedButton位置和大小


Tags: textselfboxsizeonitemlistcolor
1条回答
网友
1楼 · 发布于 2024-09-26 22:44:54

在多次阅读您的问题之后,我想您是在问如何让Rectangle跟随您的RoundedButton。最好的方法是在kv中为RoundedButton创建一个规则:

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

在python中也可以这样做,但是必须设置绑定以使Rectangle跟随RoundedButtonkv语言为您设置这些绑定

另外,请注意Widgetpossize最初设置为默认值(0,0)(100,100),并且在绘制Widget时更新。因此,您的画布正在使用这些初始默认值。由于没有设置绑定,所以当Widgetpossize更改时,画布不会更改

相关问题 更多 >

    热门问题