kivy GridLayout和AnchorLayout

时间:2016-09-22 03:18:37

标签: python-2.7 kivy grid-layout

我正在编写一个程序,使用kivy,在屏幕上显示4个图像。 我想要的目标窗口是这样的: target

窗口的背景为白色,4个图像用绿色矩形表示。屏幕比例为16:9,但图像比例为4:3。我想将这4张图像粘贴到屏幕中央。

我尝试使用GridLayout和AnchorLayout,代码如下:

from kivy.app import App
from kivy.uix.image import Image
from kivy.config import Config
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout

class MainScreen(GridLayout):

    def __init__(self, **kwargs):

        super(MainScreen, self).__init__(**kwargs)

        self.float_list = []
        self.anchor_list = []
        self.image_list = []
        self.rows = 2

        for i in range(4):
            if i % 2 == 0:
                self.anchor_list.append(AnchorLayout(anchor_x='right'))
            else:
                self.anchor_list.append(AnchorLayout(anchor_x='left'))

            self.image_list.append(Image(source='./tmp_pics/1.jpg'))

            self.anchor_list[i].add_widget(self.image_list[i])
            self.add_widget(self.anchor_list[i])

class MainDisplay(App):

    def __init__(self):
        super(MainDisplay, self).__init__()

    def build(self):

        self.mainScreen = MainScreen()

        return self.mainScreen

if __name__ == '__main__':

    Config.set('graphics', 'width', '1600')
    Config.set('graphics', 'height', '900')

    app = MainDisplay()
    app.run()

但我得到的结果是: result

请有人帮助我获得上述要求吗?

1 个答案:

答案 0 :(得分:0)

关键是将所有这些图像放在一个网格布局中,然后将其置于屏幕中间:

#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.lang import Builder

gui = '''
Screen:

    GridLayout:
        cols: 2
        rows: 2
        size_hint: None, None
        size: self.minimum_size
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}

        MyImage
        MyImage
        MyImage
        MyImage

<MyImage@AsyncImage>
    size_hint: None, None
    size: 400, 200
    source: 'http://lorempixel.com/400/200/cats/'
'''


class Test(App):

    def build(self):
        return Builder.load_string(gui)


Test().run()