强制 FloatLayout 为正方形?

Force FloatLayout to be square?

我有一个浮动布局,里面有一些小部件:

    fl = FloatLayout(size=(600,600),
                     pos_hint=({'center_x': .5, 'center_y': .5})) 

    pos1 = ImgButton(source='zulgrey.png',
                     size_hint=(0.2,0.2),
                     pos_hint=({'center_x': 0, 'center_y': .43}))

    pos2 = ImgButton(source='zulgrey.png',
                     size_hint=(0.2,0.2),
                     pos_hint=({'center_x': 0.5, 'center_y': 0.93}))

    pos3 = ImgButton(source='zulgrey.png',
                     size_hint=(0.2,0.2),
                     pos_hint=({'center_x': 1, 'center_y': .43}))

    pos4 = ImgButton(source='zulgrey.png',
                     size_hint=(0.2,0.2),
                     pos_hint=({'center_x': 0.5, 'center_y': .43}))
    fl.add_widget(cove)
    fl.add_widget(pos1)
    fl.add_widget(pos2)
    fl.add_widget(pos3)
    fl.add_widget(pos4)

但是,当我调整 window 大小时,小部件的位置会偏离我预期的位置。有没有一种方法可以强制浮动布局在调整大小时具有固定的纵横比?

嗯,是的,有一个间接和一些基本的数学。

将小部件放入另一个 FloatLayout,并将此 floatlayout 的大小绑定到一个函数以更新您当前的 floatlayout。

def update_size(self, inst, size):
    target_ratio = 16/9.
    width, height = size
    # check which size is the limiting factor
    if width / height > target_ratio:
         # window is "wider" than targeted, so the limitation is the height.
         fl.height = height
         fl.width = height * target_ratio
     else:
         fl.width = width
         fl.height = width / target_ratio

您想在 fl 上禁用 size_hint 以便该方法可以有效地设置其大小,而且,您当然希望 fl 以其父布局为中心。

fl.size_hint = None, none
fl.pos_hint = {'center': (.5, .5)}

这样解决的:

FloatLayout:
    size_hint: 1, None
    size: self.width, self.width

size_hint: 1 不一定是一个,我只是想让我的正方形填充 FloatLayout 的大小。

或者:

FloatLayout:
    size_hint: None, 1
    size: self.height, self.height