【问题标题】:AnchorLayout not centering in KivyAnchorLayout 不在 Kivy 中居中
【发布时间】:2013-12-25 22:55:57
【问题描述】:

跟进我询问的有关背景画布here 的问题,为了制作描述here 的嵌套布局,我有一个AnchorLayout 背景,我在该背景上嵌套了一个相对布局,以围绕固定大小的内部形成边距漂浮。

但是,我的嵌套小部件不在我的 AnchorLayout 内居中,尽管这既是用于锚布局的 default behavior,也被明确声明。为什么会这样?我的代码在这里:

#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')

from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import Color, Ellipse, Rectangle

class MinimalApp(App):
    title = 'My App'
    def build(self):
        root = RootLayout()
        return(root)

class RootLayout(AnchorLayout):
    pass

class Junk(RelativeLayout):
    pass

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

还有kv文件:

#:kivy 1.7.2
#:import kivy kivy

<RootLayout>:
    anchor_x: 'center'                              # I think this /is/ centered
    anchor_y: 'center' 
    canvas.before:
        Color:
            rgba: 0.4, 0.4, 0.4, 1
        Rectangle:
            pos: self.pos
            size: self.size
    Junk:
        anchor_x: 'center'                          # this is /not/ centered.
        anchor_y: 'center' 
        Label:
            text: unicode(self.center)              # this /is/ appearing
            color: 1,0,1,1
            canvas.before:
                Color:
                    rgba: 0.94, 0.94, 0.94, 1
                Rectangle:
                    size: 400,400                   # this is /not/ centered
                    Label:
                        text: unicode(self.size)    # this is /not/ appearing
                        color: 1,0,0,1

【问题讨论】:

    标签: python layout user-interface kivy


    【解决方案1】:
                Rectangle:
                    size: 400,400                   # this is /not/ centered
                    Label:
                        text: unicode(self.size)    # this is /not/ appearing
                        color: 1,0,0,1
    

    一个 Rectangle 是一个 VertexInstruction,而不是一个小部件。 VertexInstructions 是它们自己的东西,并且不受布局的大小或定位。如果您希望它们具有(例如)其父窗口小部件的大小和位置,您必须明确设置它,就像您为正确显示的早期 Rectangle 所做的那样。

    edit:同样,canvas 不是小部件,而是指作为小部件属性的画布对象。您不能在其中添加小部件,只能使用图形说明。

    对于没有出现的Label,这是因为VertexInstructions不能有像widget这样的children,所以你的kv语言定义没有意义。我很惊讶它没有抛出错误,我猜它只是默默地失败了。

    【讨论】:

    • 所以,总结一下——我的 Label 不应该是 Rectangle 的子项(因为 rectangle 是 VertexInstruction),并且我的 anchor.x,y 语句应该在 canvas.before 之前,而不是在 Label 指令之前?
    • 实际上,你的大部分 anchor_x,y 设置也没有意义。 anchor_xanchor_y 是 AnchorLayout 的属性,仅此而已。只有 RootLayout(它是 AnchorLayout 子类)使用这些属性,其他像 Junk(RelativeLayout)没有任何此类属性,因此您的设置什么都不做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2020-09-03
    • 2016-06-04
    • 2021-06-08
    • 2014-08-30
    • 2023-03-20
    相关资源
    最近更新 更多