在Kivy中添加动态小部件的大小不正确

2024-05-15 01:27:47 发布

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

我刚刚开始学习基维,我有问题的事情如何得到间隔。我正在尝试从磁盘加载图像,然后以网格方式渲染它们

然而,所有的图像都被挤压到左下角

#:kivy 1.11.0

<Gallery>:
    ScrollView:
        GridLayout:
            id: wall
            cols: 4
            size_hint_y:  None
            height: self.minimum_height

<Root>:
    gallery: gallery_id

    BoxLayout:
        orientation: 'vertical'
        size: root.size
        ActionBar:
            ActionView:
                ActionPrevious:
                ActionButton:
                    text: "Button"
                    on_release: root.clickme()

        Gallery:
            id: gallery_id
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.image import AsyncImage
from kivy.properties import (
    NumericProperty, ReferenceListProperty, ObjectProperty
)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

import glob


class Gallery(Widget):
    def doload(self):

        pngs = glob.glob('/Users/me/Desktop/*.png')[:150]

        for p in pngs:
            bl = BoxLayout(orientation='vertical')
            label = Label(text='MyLabel')
            image = AsyncImage(source=p, size_hint=(1, None), keep_ratio=True, allow_stretch=True)

            bl.add_widget(image)
            bl.add_widget(label)

            self.ids.wall.add_widget(bl)

class Root(Widget):
    gallery = ObjectProperty(None)

    def clickme(self):
        print("i've been clicked")

    def update(self):
        self.gallery.doload()

    pass



class MyApp(App):

    def build(self):
        root = Root()
        root.update()

        return root


if __name__ == '__main__':
    Window.size = (800, 600)
    MyApp().run()

这就是它看起来的样子(您可以看到图像被压扁,左下角): Screenshot

如何正确地分隔这些图像?类似这样的:Diagram

另外,当用户调整窗口大小时,有没有方法动态地确定cols中的GridLayout属性?例如,如果用户增加了窗口的宽度,那么应用程序应该支持更大的col大小。类似地,如果用户缩小窗口,应用程序应该减小col大小


Tags: from图像importselfnoneidsizedef
1条回答
网友
1楼 · 发布于 2024-05-15 01:27:47
<Gallery>:
    ScrollView:
        GridLayout:
            id: wall
            cols: 4
            size_hint_y:  None
            height: self.minimum_height

Gallery是Widget的一个子类,因此它不需要特别努力来调整其子对象的大小或位置,因此ScrollView的默认大小为(100100),位置为(0,0),因此GridLayout被放置在同一个区域中,因此您的所有图像都放在这个小区域中

解决方案是使Gallery成为适当的布局类型,例如BoxLayout

As a bonus, is there a way to dynamically determine the cols property in the GridLayout when the user resizes the window?

单位:千伏:cols: some_function_of(Window.size)

相关问题 更多 >

    热门问题