Skip to content

Photo Album

Through MicorPython programming, Identify the operation of buttons and encoders, use the official LVGL example for UI display of LCD(320*240) screens, and display example images.

import lvgl as lv

# App Name
NAME = "Photo Album"

# App Icon
ICON = "A:apps/photo_album/assets/icon.png"

# LVGL widgets
scr = None

# image position
photo = [
    "A:apps/photo_album/assets/1.jpg",
    "A:apps/photo_album/assets/2.jpg",
    "A:apps/photo_album/assets/3.jpg",
    "A:apps/photo_album/assets/4.jpg"
]

# current image index
photo_index = 0

# ===============================================================

def event_handler(e):
    # When a specific event occurs, LVGL will invoke/call the function to handle the event.
    global photo_index
    e_code = e.get_code()
    if e_code == lv.EVENT.KEY:
        e_key = e.get_key()

        # Rotate the encoder anti-clockwise to select the next image.
        if e_key == lv.KEY.RIGHT: photo_index = (photo_index + 1) % 4
        # Rotate the encoder clockwise to select the previous image.
        elif e_key == lv.KEY.LEFT: photo_index = (photo_index - 1) % 4

        # Update the background image.
        e.get_target_obj().set_style_bg_img_src(photo[photo_index], lv.PART.MAIN)
    elif e_code == lv.EVENT.FOCUSED:
        # If not in edit mode, set to edit mode.
        if not lv.group_get_default().get_editing(): lv.group_get_default().set_editing(True)

async def on_stop():
    # User triggered to leave this app, all functions should be deactivated
    print('on stop')
    global scr
    if scr:
        # Delete the LVGL widgets.
        scr.clean()
        scr.del_async()
        scr = None


async def on_start():
    # User triggered to enter this app, all functions should be activated
    print('on start')
    global scr
    # Create the LVGL widgets.
    scr = lv.obj()
    # Load the LVGL widgets.
    lv.scr_load(scr)

    # Set the background image and background color for the widgets.
    scr.set_style_bg_img_src(photo[photo_index], lv.PART.MAIN)
    scr.set_style_bg_color(lv.color_hex3(0x000), lv.PART.MAIN)

    # Set the event callback for the widgets.
    scr.add_event(event_handler, lv.EVENT.ALL, None)

    # Focus the key operation on the current widgets.
    lv.group_get_default().add_obj(scr)
    lv.group_focus_obj(scr)
    lv.group_get_default().set_editing(True)