Search code examples
kivykivy-languagekivymd

Generalize the KivyMD image-list example


https://kivymd.readthedocs.io/en/latest/components/image-list/#smarttilewithstar

How do you generalize the kiymd doc image-list example so the image display logic is outside of the kv file?

This is my attempt but it displays all the images in the top row only (and also leaves the first image on the left blank). Thanks.

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.imagelist import SmartTile
from kivymd.uix.gridlayout import MDGridLayout

img = ["00.jpg", "03.jpg", "13.jpg", "15.jpg", "24.jpg", "28.jpg", "29.jpg", "33.jpg", "34.jpg"]

Builder.load_string('''

<MyTile@SmartTile>
    size_hint_y: None
    height: "240dp"

<CatScreen>:
    
    ScrollView:
        id: scroll

        MDGridLayout:
            id: grid
            cols: 3
            adaptive_height: True
            padding: dp(4), dp(4)
            spacing: dp(4)

            MyTile:
''')


class CatScreen(Screen):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def display_image(self):
        for im in img:
            self.ids.grid.add_widget(SmartTile(source = im))
        return self


class CatApp(MDApp):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def build(self):
        self.cs = CatScreen()
        return self.cs.display_image()

CatApp().run()

Solution

  • import os
    
    from kivy.factory import Factory as F
    from kivy.lang import Builder
    from kivymd.app import MDApp
    from kivy.uix.screenmanager import Screen
    from kivymd.uix.imagelist import SmartTile
    
    ######################################
    # this part of the code is to take images from my folder
    img = []
    PATH = "/root/Pictures" # source folder
    for i in os.listdir(PATH):
        if ".png" in i:
            img.append(PATH + "/" + i)
    ######################################
    
    Builder.load_string('''
    
    <MyTile@SmartTile>:
        size_hint_y: None
        height: "240dp"
    
    <CatScreen>:
        
        ScrollView:
            id: scroll
    
            MDGridLayout:
                id: grid
                cols: 3
                adaptive_height: True
                padding: dp(4), dp(4)
                spacing: dp(4)
    
                MyTile:
    ''')
    
    
    class CatScreen(Screen):
    
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
        
        def display_image(self):
            for im in img:
                self.ids.grid.add_widget(F.MyTile(source=im))
            return self
    
    
    class CatApp(MDApp):
    
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
        
        def build(self):
            self.cs = CatScreen()
            return self.cs.display_image()
    
    CatApp().run()