Skip to main content
 首页 » 编程设计

python之kivy anchor 布局不锚定

2024年10月24日9softidea

我正在尝试让名为“number”的标签直接显示在椭圆的中心上方。我已经尝试将两者放在相同的布局中,不同的布局中,在 AnchorLayouts 和 RelativeLayouts 中,但我一直无法弄清楚如何做到这一点。

这是我的 python 的测试版本,显示了同样的问题:

class BugTester(FloatLayout): 
    def __init__(self): 
        super().__init__() 
        for i in range(1,6): 
            temp  = GamePiece(5, "Red") 
            temp.pos = (i*100,i*200) 
            self.add_widget(temp) 
 
 
class BugTestingApp(App): 
    def build(self): 
        return BugTester() 
 
class GamePiece(ToggleButton): 
 
    def __init__(self, number, color, **kwargs): 
        self.number = number 
        self.player_color = color 
        self.background_normal = "5.png" 
        super(GamePiece, self).__init__() 
 
 
if __name__ == '__main__': 
    BugTestingApp().run() 

还有我的基维:

<BugTester>: 
    Button: 
        background_disabled_normal: "background.jpg" 
        disabled: True 
 
 
<GamePiece>: 
    id: gamepiece 
    size_hint:(None, None) 
    group: self.player_color 
    border: (0,0,0,0) 
 
 
    AnchorLayout: 
        id: layout 
        center: root.center 
        on_size: self.size = root.size 
        anchor_x: "left" 
        anchor_y: "bottom" 
 
        canvas: 
            Color: 
                rgba: 0,0,0,1 
            Ellipse: 
            #this is the ellipse in question 
                id: circle 
                size: (root.width/2.5, root.height/3) 
                #pos: -15, -20 
                pos: root.pos 
 
        Label: 
        #this is the label I want centered over the ellipse 
            id: number 
            text: str(root.number) 
            color: (1,1,1,1) 
            font_size: root.height/4 
            bold: True 
            #pos: root.pos 

这是它目前的样子:(按下其中一个切换按钮用于说明目的)

请您参考如下方法:

在您的示例中,标签与其所属的 anchor 布局一样大,因此您无法移动它们。

如果您希望它们具有其他尺寸,则禁用 size_hint,并使用固定的 size(例如,与椭圆一样大):

Label: 
#this is the label I want centered over the ellipse 
    size_hint: None, None 
    size: (root.width/2.5, root.height/3) 
    id: number 
    text: str(root.number) 
    color: (1,1,1,1) 
    font_size: root.height/4 
    bold: True 
    #pos: root.pos 

结果: