Contents
4.1 Box Model
LVGL box model = a 4-layer structure, which consists of, from the inside out:
Hierarchy | Function | Code Correspondence | Effect / Description |
Content Area (Content) | The actual content placed inside the box. |
| Located at the innermost layer, where text and icons are displayed; it will be wrapped by padding and will not directly stick to the border. |
Padding | The blank space between the content and the border. |
| Leave 15 pixels of blank space on the top, bottom, left and right sides respectively to keep the content away from the edges and make the interface more aesthetically pleasing. |
Border | The outer contour line of the box. |
| It wraps the padding and the content area to form the boundary of the box. |
Shadow | The projection on the exterior of the box. | Attributes such as shadow width and offset | It is only responsible for visual beautification, does not occupy layout space, and will not affect the size or position of the box. |
Summary | The LVGL box model consists of a four-layer structure. | Content + padding + border + shadow | Total size of the control = content + padding + border; shadows are not included in the actual layout size. |
The sample code is as follows:
import display_driver
import lvgl as lv
lv.init()
# Initialize screen
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)
# 1. Create container (box model carrier)
obj = lv.obj(scr)
obj.set_pos(80, 80) # Position of the box on the screen
obj.set_size(120, 120) # Total size of the box
# 2. Core: box model styles (simplified, keeping only key attributes)
style = lv.style_t()
# --------- Padding: blank space inside the box ---------
style.set_pad_all(15) # Uniform padding on all sides
# --------- Background (base color of the content area) ---------
style.set_bg_color(lv.color_hex(0xFF0000)) # Red background
style.set_bg_opa(255)
# --------- Border: the box's border ---------
style.set_border_width(3) # Border width
style.set_border_color(lv.color_hex(0x00FF00)) # Green border
# --------- Shadow: drop shadow outside the box ---------
style.set_shadow_width(8)
style.set_shadow_color(lv.color_hex(0x00FFFF))
style.set_shadow_offset_x(5)
style.set_shadow_offset_y(5)
# Apply style
obj.add_style(style, lv.STATE.DEFAULT)
# 3. Content area: label (placed inside the box, squeezed by the padding)
label = lv.label(obj)
label.set_text("BOX")
label.center() # Centered inside the box
label.set_style_text_color(lv.color_hex(0xFFFFFF), 0)
# Show interface
lv.screen_load(scr)
This code transforms the abstract "box model" into an intuitive and visible interface by combining a red container, internal labels, and visual layering, which perfectly corresponds to the four-layer structure of LVGL widgets:
- Innermost layer: Content Area
- Corresponding code:
label = lv.label(obj)+label.set_text("BOX") - Screenshot display: white text in the middle of the red background
BOX - Core Meaning: The "content" actually carried by the control (such as text, icons, sub-controls, etc.), which is the innermost layer of the box model.
- Note: The content area will be "pushed" to the center by the padding and will not be directly attached to the border.
- Corresponding code:
- Layer 2: Padding
- Corresponding code:
style.set_pad_all (15)(add 15px padding around the container) - Screenshot Representation: The area with a red background (the part within the green border and excluding the text)
- Core Meaning: the blank space between the content area and the border, which serves to prevent the content from sticking to the border and makes the interface more aesthetically pleasing.
- Intuitive verification: If you modify the code to
style.set_pad_left (30), you will see the text pushed to the right, and the "squeezing effect" of the padding will be more obvious.
- Corresponding code:
- Layer 3: Border
- Corresponding code:
style.set_border_width(3)+set_border_color(0x00FF00) - Screenshot Performance: The circle of green outline surrounding the red background
- Core meaning: The "outer boundary" of the box, which wraps the padding and content area and defines the visible edge of the control.
- Size impact: The border adds to the visual size of the control; for instance, the 3px border here makes the box appear thicker overall.
- Corresponding code:
- Outermost Layer: Shadow
- Corresponding code:
style.set_shadow_*series attributes (cyan, offset 5px, width 8px) - Screenshot performance: the light cyan blurred shadow at the bottom right of the green border
- Core meaning: the "visual projection" of a box, which does not occupy layout space and is merely a decorative effect used to enhance a sense of three-dimensionality and distinguish hierarchical levels.
- Key Difference: Shadows do not alter the position or dimensions of the box, nor do they affect the layout of other controls — they are purely visual decorations.
- Corresponding code:
4.2 Position and Dimension Settings
In the following code, a rectangular control with a custom visual style is implemented: after initializing LVGL, set the screen background to black, create a 100×100 pixel square object at the screen coordinate (100,100), configure styles such as red background, green border, and green translucent shadow for this object, and finally load the screen to complete the rendering. Eventually, a red square with green border and shadow will be displayed on the screen:
import display_driver
import lvgl as lv
lv.init()
#Get the currently active screen object
scr = lv.screen_active()
#Set the screen background color to black
scr.set_style_bg_color(lv.color_hex(0x000000), 0)
#Create the object
obj = lv.obj(scr)
#Set the object position and size
obj.set_pos(100, 100) #Set the top-left coordinates of the object
obj.set_size(100, 100) #Set the width and height of the object
#Create a style
style_obj = lv.style_t()
#Border and background
style_obj .set_pad_all(10) #Set padding in all four directions
#style_obj .set_pad_left(10) #Set left padding
#style_obj .set_pad_right(10) #Set right padding
#style_obj .set_pad_top(10) #Set top padding
#style_obj .set_pad_bottom(10) #Set bottom padding
style_obj .set_bg_opa(255) #Set background opacity; 0 is fully transparent
style_obj .set_bg_color(lv.color_hex(0xFF0000)) #Set background color
style_obj .set_border_color(lv.color_hex(0x00FF00)) #Set border color
style_obj .set_border_width(2) #Set border width
style_obj .set_border_opa(255) #Set border opacity; 0 is fully transparent
#Shadow style
style_obj .set_shadow_color(lv.color_hex(0x00FF00))#Set shadow color
style_obj .set_shadow_width(10)#Set shadow width (shadow spread range)
style_obj .set_shadow_opa(50)#Set shadow opacity
style_obj .set_shadow_offset_x(10)#Set shadow horizontal offset
style_obj .set_shadow_offset_y(10)#Set shadow horizontal offset
#Apply the style
obj.add_style(style_obj , lv.STATE.DEFAULT)
# Load the screen
lv.screen_load(scr)

4.2.1 Modify the position and size of the object
We can use the following methods to modify the position and size of an object:
#Set the object position and size
obj.set_pos(150, 150) #Set the top-left coordinates of the object
obj.set_size(120, 120) #Set the width and height of the object
4.2.2 Internal Alignment (Typesetting within the Parent Container)
Here is an example of internal alignment:

# ============== Internal alignment: auto layout inside the parent container obj ==============
# 1. Create child widget (placed inside obj)
child = lv.obj(obj)
child.set_size(40, 40) # Child widget size
# 2. Give the child widget a blue style (for easy distinction)
style_child = lv.style_t()
style_child.set_bg_color(lv.color_hex(0x00AAFF))
style_child.set_bg_opa(255)
child.add_style(style_child, lv.STATE.DEFAULT)
# 3. ✅ Core: internal alignment API (run any one line to see different effects)
child.align(lv.ALIGN.CENTER, 0, 0) # Exact center of the parent container (no offset)
# child.align(lv.ALIGN.TOP_LEFT, 5, 5) # Top-left of the parent container, offset inward by (5,5)
# child.align(lv.ALIGN.BOTTOM_RIGHT, -5, -5) # Bottom-right of the parent container, offset inward by (-5,-5)
# child.align(lv.ALIGN.LEFT_MID, 5, 0) # Left-center of the parent container, offset 5px to the right4.2.3 External Alignment (Align with Other Controls)

# ============== External alignment: align outside the obj widget ==============
# 1. First create a reference widget (a button here; it can be any other widget)
ref_btn = lv.button(scr)
ref_btn.set_pos(200, 100)
ref_btn.set_size(60, 30)
ref_label = lv.label(ref_btn)
ref_label.set_text("REF")
ref_label.center()
# 2. Create the label widget to be aligned
label = lv.label(scr)
label.set_text("OUT_LABEL")
label.set_style_text_color(lv.color_hex(0xFFFFFF), 0) # White text
# 3. ✅ Core: external alignment API (run any one line to see different effects)
label.align_to(ref_btn, lv.ALIGN.OUT_TOP_MID, 0, -10) # Top-center of the reference button, offset 10px upward
# label.align_to(ref_btn, lv.ALIGN.OUT_RIGHT_MID, 10, 0) # Right-center of the reference button, offset 10px to the right
# label.align_to(ref_btn, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 10) # Bottom-left of the reference button, offset 10px downward4.3 Translation
It uses the "relative offset" based on the object's current position to solve the problem that "objects with different initial positions will offset by the same distance during interaction"(e. g., a button moves upward when pressed). Here is an mpy example:
# Initialize
import display_driver
import lvgl as lv
# Create a button with a label
lv.init()
scr = lv.screen_active()
btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)
# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100) # Default width 100 pixels
# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120) # Width 120 pixels when pressed
# Create the pressed state style, set y-axis translation to -20 pixels (move up 20)
style_pressed.set_translate_y(-20)
# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)
lv.screen_load(scr)

Furthermore, there are two key features:
- Percentage support: The percentage for translation is based on the object's own dimensions (not the parent object). For example,
set_translate_x (lv.pct (50))→ offset to the right by 50% of the object's own width; - Layout Compatibility: The translation takes effect after layout calculation, which does not affect the layout, but will trigger the recalculation of scroll bars / content Self-Adaptation (actually changing the position).
4.4 Transformation
"Visual scaling" based on the object's current size only alters the display effect without affecting its actual dimensions (layout, scrollbars, and content Self-Adaptation will not detect this). mpy example (enlarging when the button is pressed):
# Initialize
import display_driver
import lvgl as lv
# Create a button with a label
lv.init()
scr = lv.screen_active()
btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)
# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100) # Default width 100 pixels
# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120) # Width 120 pixels when pressed
# Expand width/height outward by 10 pixels each (visually +20 in width, +20 in height)
style_pressed.set_transform_width(10)
style_pressed.set_transform_height(10)
# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)
lv.screen_load(scr)

| Feature | Translation | Transformation |
|---|---|---|
| Position / size | Changes the real position | Visual scaling only; the real size is unchanged |
| Layout Impact | Affects layout / scrollbar | Does not affect layout / scrollbar |
| Purpose | Position offset during interaction | Visual scaling during interaction (no layout interference) |
4.5 Layout System
Layout is a core mechanism in LVGL for automatically arranging widgets, which can replace manually calling set_pos () to calculate coordinates, making the interface more structured and easier to maintain, and is especially suitable for GUI development with limited screen sizes in embedded scenarios.
- Core Objective: Enable controls such as buttons and text to be automatically arranged according to set rules, eliminating the need for tedious position calculation.
- Typical scenarios: horizontal menus, vertical lists, numeric keypads, function matrices, etc.
The core concepts include the following. First, the layout container:
- Layout carrier: Create a blank container via
lv.obj (scr), and all controls that require automatic arrangement must be mounted inside this container. - A container itself is also a control: you can use
set_size (width, height)to limit the layout area, andset_pos (X, Y)to adjust the position of the container on the screen. - Parent-child hierarchy: The container acts as the "parent control", while buttons/labels serve as "child controls"; the layout rules only apply to the direct child controls of the container.
Layout types include:
| Layout Type | Applicable scenarios | Core characteristics |
|---|---|---|
| Flex layout | Linear arrangement (one row / one column), such as horizontal menus and vertical settings lists | Child widgets are automatically arranged along a single direction (horizontal / vertical), with spacing handled automatically |
| Grid layout | Two-dimensional table arrangement, such as number keypads and 3×3 function matrices | Divides the container into cells of multiple rows and columns; child widgets can be precisely assigned to specified cells |
The basic layout process is as follows:
- Create Container:
lv.obj (scr)—— Generates an empty container for holding the layout - Enable Layout:
set_layout (layout_type)—— Select Flex or Grid mode - Configuration Rules: Set parameters such as direction, spacing, grid rows and columns, etc.
- Add Control: Add child controls such as buttons and labels to the container — the controls will be automatically arranged according to the rules
- Load Display:
lv.screen_load (scr)—— Render the layout to the screen


4.5.1 Row/Column Arrangement (Flex Layout)
The following code is a standard example of LVGL MicroPython flex layout, which implements horizontal row arrangement and vertical column arrangement of buttons:
import display_driver
import lvgl as lv
# Initialize LVGL
lv.init()
scr = lv.screen_active()
# Generic button callback function
def btn_cb(e):
print("按钮点击")
# Minimal button creation
def make_btn(parent, text):
btn = lv.button(parent)
btn.set_size(70, 40)
btn.add_event_cb(btn_cb, lv.EVENT.PRESSED, None)
label = lv.label(btn)
label.set_text(text)
label.center()
return btn
# ============== 1. Horizontal row layout (one horizontal row) ==============
row = lv.obj(scr)
row.set_size(320, 60)
row.set_pos(10, 10)
row.set_layout(lv.LAYOUT.FLEX) # Correct: flex layout
row.set_style_flex_flow(lv.FLEX_FLOW.ROW, 0) # Correct: horizontal row
row.set_style_pad_column(10, 0) # Horizontal spacing between buttons
# Automatically arrange 3 buttons horizontally
make_btn(row, "A1")
make_btn(row, "A2")
make_btn(row, "A3")
# ============== 2. Vertical column layout (one vertical column) ==============
col = lv.obj(scr)
col.set_size(90, 220)
col.set_pos(10, 80)
col.set_layout(lv.LAYOUT.FLEX) # Correct: flex layout
col.set_style_flex_flow(lv.FLEX_FLOW.COLUMN, 0) # Correct: vertical column
col.set_style_pad_row(10, 0) # Vertical spacing between buttons
# Automatically arrange 4 buttons vertically
make_btn(col, "1A")
make_btn(col, "1B")
make_btn(col, "1C")
make_btn(col, "1D")
lv.screen_load(scr)


In the code above, we performed the following operations on the layout container:
lv.obj (scr): Creates a blank container for holding buttons and implementing automatic layoutset_size (width, height): Set the size of the container to define the display area for the layout.set_pos (X coordinate, Y coordinate): Set the position of the container on the screen (the top-left corner serves as the coordinate origin)
Among these, the core attribute settings of Flex layout include:
set_layout (lv.LAYOUT.FLEX): Enable flex layout to allow child widgets to be arranged automatically; this is the core toggle for layout functionalitylv.LAYOUT.FLEX: Enumeration value, indicating that the layout type is flex layout
The layout direction attributes include:
set_style_flex_flow (direction, 0): Set the arrangement direction of the flex layoutlv.FLEX_FLOW.ROW: Horizontal arrangement (left to right)lv.FLEX_FLOW.COLUMN: Vertical and longitudinal arrangement (from top to bottom)
Spacing control attributes include:
set_style_pad_column (pixels, 0): Set the column spacing between buttons when arranged horizontally.set_style_pad_row (pixels, 0): Set the row spacing between buttons when arranged vertically
Core Fundamentals of Flex Layout
Layout Direction (Flow)
Controlling the arrangement direction of child controls is the core switch of Flex layout:
lv.FLEX_FLOW.ROW: Horizontal arrangement (left to right)lv.FLEX_FLOW.COLUMN: Vertical and longitudinal arrangement (from top to bottom)
Spacing Control
Avoid overcrowded controls and optimize the aesthetic appeal of the interface:
- When arranged horizontally:
set_style_pad_column (pixels, 0)—— sets the horizontal spacing between child controls - When arranged vertically:
set_style_pad_row (pixels, 0)—— Sets the vertical spacing between child controls
Alignment Logic
Child widgets will automatically fill along the layout direction, and their position within the container can be adjusted via alignment properties (such as lv.FLEX_ALIGN.CENTER).
4.5.2 Two-Dimensional Grid Arrangement (Grid Layout)
The code below implements a two-dimensional grid layout, which creates a regular button grid with 2 rows and 3 columns based on the officially revised API:
import display_driver
import lvgl as lv
# Initialize LVGL
lv.init()
scr = lv.screen_active()
# Click callback
def btn_cb(e):
print("按钮点击")
# Create button
def make_btn(parent, text):
btn = lv.button(parent)
btn.set_size(70, 40)
btn.add_event_cb(btn_cb, lv.EVENT.PRESSED, None)
label = lv.label(btn)
label.set_text(text)
label.center()
return btn
# ==================== 2D grid layout (2 rows, 3 columns) ====================
grid = lv.obj(scr)
grid.set_size(280, 150)
grid.set_pos(20, 20)
grid.set_layout(lv.LAYOUT.GRID)
# Define 3 columns + 2 rows
col_dsc = [80, 80, 80, lv.GRID_TEMPLATE_LAST]
row_dsc = [50, 50, lv.GRID_TEMPLATE_LAST]
# Correct API
grid.set_grid_dsc_array(col_dsc, row_dsc)
# Spacing
grid.set_style_pad_row(10, 0)
grid.set_style_pad_column(10, 0)
# Loop to create buttons + set grid positions strictly following your API
for i in range(6):
col = i % 3 # Columns: 0,1,2
row = i // 3 # Rows: 0,0,0,1,1,1
btn = make_btn(grid, str(i+1))
# ✅ Strictly matches the 6 parameters you provided!!!
btn.set_grid_cell(
lv.GRID_ALIGN.CENTER, # 1. column_align: column alignment
col, # 2. col_pos: column position
1, # 3. col_span: spans 1 column
lv.GRID_ALIGN.CENTER, # 4. row_align: row alignment (must be passed in your API!)
row, # 5. row_pos: row position
1 # 6. row_span: spans 1 row
)
lv.screen_load(scr)
In the code above, after initializing the LVGL graphics library and the screen container, we encapsulated a general button creation function with click response. By enabling GRID grid layout, defining row and column size descriptors, and setting spacing, we then generated buttons in a loop and strictly followed the 6-parameter specification of set_grid_cell to specify the grid alignment, position and span of each button, and finally loaded the screen to implement a neatly arranged grid interface, which fully demonstrates the core usage of LVGL grid layout.
The core APIs and attributes are defined as follows:
- Grid container creation
lv.obj (scr)creates a blank container (the carrier of the layout);set_layout (lv.LAYOUT.GRID)enables the grid layout (core: divides the container into independent cells with multiple rows and columns to realize two-dimensional regular arrangement). - Grid structure definition:
col_dsc/row_dscis a grid description array used to define the column widths and line-height of the grid; in the example, 3 columns (80px per column) and 2 rows (50px per row) are defined;lv.GRID_TEMPLATE_LASTis a fixed syntax of LVGL that marks the end of the array. - Grid Frame Binding
set_grid_dsc_array ()This is a core grid API that applies the defined row and column dimensions to the container to complete the construction of the grid cell frame. - Network Spacing Settings:
set_style_pad_row/set_style_pad_columnrespectively set the row spacing and column spacing of cells to avoid overcrowded buttons, which is a basic optimization for GUI layout. - Precise Control Positioning:
set_grid_cell ()assigns cells to child controls. Its 6 parameters strictly follow the LVGL grid rules: center alignment in column, index of the column, occupying 1 column, center alignment in row, index of the row, occupying 1 row, ensuring each button is fixed within the corresponding grid.
Core Fundamentals of Grid Layout
Grid Descriptor (col_dsc / row_dsc)
Defines the column width and line-height of the grid, serving as the "skeleton" of Grid layout:
- Format:
[col_width_1, col_width_2,. .., lv.GRID_TEMPLATE_LAST],lv.GRID_TEMPLATE_LASTis a fixed end marker. - Example:
col_dsc = [80,80,80, lv.GRID_TEMPLATE_LAST]→ Defines 3 columns, each with a width of 80px
Grid Frame Binding
set_grid_dsc_array (col_dsc, row_dsc)—— Apply the defined row and column dimensions to the container to complete the construction of the cell framework.
Precise Control Positioning (set_grid_cell)
Assign specific cells to child controls, with the 6 parameters strictly corresponding to the LVGL grid rules:
column_align: Column alignment method (e. g.,lv.GRID_ALIGN.CENTERfor center alignment)col_pos: the index of the column where the item is located (starting from 0)col_span: Number of columns occupied (usually 1)row_align: Row alignment moderow_pos: the index of the row where the element is located (starting from 0)row_span: Number of rows occupied (usually 1)
4.6 Scrolling
Scrolling is the core interaction mechanism in LVGL that enables users to swipe and browse when content exceeds the container, which is widely used in scenarios such as lists, long text, and carousels, with a design that fits the operation intuition of embedded devices.
The essence of scrolling lies in the "size difference" between the container and the content:
- Scrolling container: The parent element (e. g., a small box) that acts as the "viewport"; it has a fixed size and defines the area visible to the user.
- Child content: Refers to the controls placed inside a container (such as buttons, images, and text). When the total size of these child content exceeds the visible area of the container, the container will automatically switch to a "scrollable state", allowing users to swipe to view all the content.
- Trigger Condition: The total width of child objects > container width (for horizontal scrolling), or the total height of child objects > container height (for vertical scrolling); scrolling will be triggered as long as either of the two conditions is met.
It should be noted that LVGL does not support diagonal scrolling, and you can only choose one of the following two directions:
- Vertical Scroll (VER): Slide up and down, suitable for lists and long text (the most commonly used type).
- Horizontal Scroll (HOR): Slide left and right, suitable for carousels and horizontal menus.
- No Scrolling (NONE): Locks the container, making it impossible to scroll even when the content overflows.
The scrollbar is a standalone component (LV_PART_SCROLLBAR) of the container, used to visually indicate:
- Where has the scrollbar scrolled to (slider position).
- How much content remains unread (slider length).
Scrollbars can have their styles (color, thickness, spacing) customized individually, and their show/hide logic can also be controlled.
A complete scrolling operation goes through three key stages, which can be monitored via event listeners:
- Scroll Begin (SCROLL_BEGIN): The user presses the screen with a finger and swipes, officially triggering the scrolling action.
- Scrolling (SCROLL): Triggered once every time the position changes, suitable for real-time UI updates.
- Scroll End (SCROLL_END): The user lifts their finger, and the scrolling comes to a complete stop. This state is suitable for implementing finalization logic (such as loading additional content).
LVGL MicroPython scrolling function API cheat sheet is as follows:
Category | Method | Function | Description / Scenario |
Scroll Basic Configuration |
| Set the allowed scrolling direction | It supports controlling horizontal scrolling, vertical scrolling, or disabling scrolling entirely. |
Scroll Basic Configuration |
| Set the scrollbar display mode | The scrollbar can be configured to automatically show, always show, or be hidden. |
Scroll Basic Configuration |
| Set scroll snapping effect | It will automatically align to the specified position after you release it, which is suitable for scenarios such as carousel carousels. |
Scroll Control Method |
| Relative Scrolling | Scroll based on the offset from the current position |
Scroll Control Method |
| Absolute Scrolling | Scroll directly to the specified |
Scroll Control Method |
| Independently control horizontal / vertical scrolling | Control the scrolling position in the X-axis or Y-axis direction respectively. |
Scroll Control Method |
| Automatically scroll to display the current control | Make the current control fully displayed on the screen, which is often used for automatic element positioning. |
Scroll State Acquisition |
| Get the current scroll coordinates | Returns the current X/Y scroll position of the container. |
Scroll State Acquisition |
| Obtain the vertical boundaries | Returns the maximum scroll boundaries at the top / bottom in the vertical direction. |
Scroll State Acquisition |
| Get the horizontal boundary | Returns the maximum scroll boundary on the left / right side in the horizontal direction. |

Scroll Direction Setting:
| Function | Related code |
|---|---|
| Vertical scrolling | container.set_scroll_dir(lv.DIR.VER) |
| Horizontal scrolling | container.set_scroll_dir(lv.DIR.HOR) |
| Scrolling disabled | container.set_scroll_dir(lv.DIR.NONE) |
| Scrollbar shown automatically | container.set_scrollbar_mode(lv.SCROLLBAR_MODE.AUTO) |
The LVGL scrollbar modes are as follows:
| Enum constant | Meaning | Core function (beginner-friendly) |
|---|---|---|
| lv.SCROLLBAR_MODE.OFF | Off | Never shows the scrollbar, completely hidden |
| lv.SCROLLBAR_MODE.ON | Always shown | Always shows the scrollbar, whether or not the content overflows |
| lv.SCROLLBAR_MODE.ACTIVE | Shown while scrolling | Shown only while the finger is swiping / scrolling, and hidden once it stops |
| lv.SCROLLBAR_MODE.AUTO | Automatic display | Recommended by default; shows the scrollbar only when the content overflows the container |
LVGL provides three types of core events for capturing the entire lifecycle of scrolling:

Core Event | Meaning of Core Events |
SCROLL_BEGIN | Triggered when scrolling starts, the parameters of the scrolling animation (such as animation duration and easing curve) can be modified; |
SCROLL_END | Triggered when scrolling ends, it is suitable for executing the final logic after scrolling (such as loading more content and updating status); |
SCROLL | Triggered during the scrolling process (on every position change), it is suitable for real-time monitoring of scroll position (e. g. dynamically updating UI elements, recording scroll offset). |
4.6.1 Scrolling Basic Demo
In the following case, we will create a small container, place a large number of buttons in it (the content will exceed the container size), which automatically supports scrolling, so you can intuitively feel the trigger conditions for scrolling.
import display_driver
import lvgl as lv
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0) # Black background
# ==================== 1. Create scroll container (parent object) ====================
container = lv.obj(scr)
container.set_size(200, 150) # Container size is very small (limits the display area)
container.set_pos(50, 50) # Container position
container.set_scroll_dir(lv.DIR.VER) # Enable [vertical scrolling] (core)
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.AUTO) # Scrollbar shows automatically
# ==================== 2. Create many child buttons (content exceeds the container, triggering scrolling) ====================
for i in range(10):
btn = lv.button(container)
btn.set_size(180, 30)
btn.set_pos(10, 10 + i*40) # Arrange buttons vertically
label = lv.label(btn)
label.set_text(f"Button {i+1}")
label.center()
lv.screen_load(scr)

Here, we can see that:
- Scroll trigger condition: The container is small, with a large number of buttons that exceed the container's range → automatically switches to scrollable mode;
- Scroll Container:
containerrefers to the parent scrolling container, and all buttons are its child objects; - Scrolling direction: We have configured vertical scrolling only, which complies with LVGL's rule of "supporting single-direction scrolling only";
- Scrollbar: It will automatically appear when you swipe the screen, and hide when you stop swiping.
We can also set different scrolling directions for viewing:
| Function | Related code |
|---|---|
| Vertical scrolling | container.set_scroll_dir(lv.DIR.VER) |
| Horizontal scrolling | container.set_scroll_dir(lv.DIR.HOR) |
| Scrolling disabled | container.set_scroll_dir(lv.DIR.NONE) |
Here is the horizontal scroll:

The following is to disable scrolling:

If we do not specify the scrolling direction, it will be automatically set based on the sizes of the container and the internal controls (both vertical and horizontal directions are supported):
# The comment on the line below
# container.set_scroll_dir(lv.DIR.VER)
We can also set the scrolling mode; the following is the case where the scrollbar is not displayed:
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.OFF)
The following is to display the scrollbar when scrolling:
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.ACTIVE)
The following is the one that always displays the scrollbar:
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.AUTO)
4.6.2 Scroll Event Listening
Based on Case 1, monitor the scroll start and scroll end events, and print logs in the terminal so that beginners can intuitively observe the changes in scroll status.
import display_driver
import lvgl as lv
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)
# ==================== Scroll event callback function ====================
def scroll_event_callback(e):
target = e.get_target() # Get the object that triggered the event (the scroll container)
event_code = e.get_code() # Get the event type
# Check for the scroll event
if event_code == lv.EVENT.SCROLL_BEGIN:
print("📜 滚动开始了!")
elif event_code == lv.EVENT.SCROLL_END:
print("📜 滚动完全结束!")
# ==================== 1. Create the scroll container ====================
container = lv.obj(scr)
container.set_size(200, 150)
container.set_pos(50, 50)
container.set_scroll_dir(lv.DIR.VER)
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.ACTIVE) # Show scrollbar only while scrolling
# ==================== 2. Bind the scroll listener event (core) ====================
container.add_event_cb(scroll_event_callback, lv.EVENT.SCROLL_BEGIN, None)
container.add_event_cb(scroll_event_callback, lv.EVENT.SCROLL_END, None)
# ==================== 3. Create child buttons ====================
for i in range(10):
btn = lv.button(container)
btn.set_size(180, 30)
btn.set_pos(10, 10 + i*40)
label = lv.label(btn)
label.set_text(f"Button:{i+1}")
label.center()
lv.screen_load(scr)
Here, we bind an event callback to the scroll container, so that the system will automatically notify us when the screen is swiped.
The two core events are as follows:
lv.EVENT.SCROLL_BEGIN: Finger swipe / scroll starts → printScroll started;lv.EVENT.SCROLL_END: When scrolling comes to a complete stop → printScroll ended;
Common usage scenarios include loading more content when scrolling to the bottom, hiding controls while scrolling, and so on.
4.7 Layer Management
The layers in LVGL essentially control the rendering hierarchy of UI elements (i. e., "which object appears on top of another"), and there are two core layer systems:
- First, the default hierarchy of ordinary objects based on their "creation order";
- Second, there are special system layers (top/sys/bottom) that are globally visible.
To be precise:
- Hierarchy Rules: Objects are stacked by default in the order they are created, and their hierarchy can be adjusted manually to achieve overlay effects such as pop-up windows and floating windows.
- Special layers: The top/system layers are used to display global pop-ups and status bars; the bottom layers are for background elements to ensure a clear hierarchy of priorities.

4.7.1 Creation Order: Default Hierarchy Rules
LVGL follows the default "later-created objects on top" principle: newly created objects (and their child objects) are drawn on top of older objects (and their child objects), which may cover the display area of the older objects.
# Initialize
import display_driver
import lvgl as lv
# Create a button with a label
lv.init()
scr = lv.screen_active()
# Create the first button (created first, lower in z-order)
btn1 = lv.button(scr)
# Position (x=60, y=40)
btn1.set_pos(60, 40)
label1 = lv.label(btn1)
label1.set_text("Button 1")
# Create the second button (created later, higher in z-order, covers the overlapping area of btn1)
btn2 = lv.button(scr)
# Position (x=60, y=60)
btn2.set_pos(60, 60)
label2 = lv.label(btn2)
label2.set_text("Button 2")
lv.screen_load(scr)
4.7.2 Modify Hierarchy: Adjust the Display Order of Objects Manually
When the default creation order fails to meet requirements (e. g., moving a bottom-layer button to the top layer), LVGL provides 4 explicit ways to modify the layer hierarchy, which can be directly invoked via the corresponding object methods in MicroPython:
4.7.2.1 Pin to Top / Pin to Bottom (Most Commonly Used)
| Method (mpy) | Purpose |
|---|---|
| obj.move_foreground() | Move the object (and its children) to the top layer of the parent container |
| obj.move_background() | Move the object (and its children) to the bottom layer of the parent container |

mpy example: bring the previously created btn1 to the top layer (to cover btn2)
# Move btn1 to the topmost layer of the parent container (scr)
btn1.move_foreground()4.7.2.2 Move to the specified index position
Each child object of a parent container has an "index value", which determines its hierarchy:
- Index
0: the bottom layer of the parent container; - Index
Number of child objects + 1: the upper layer of the parent container; - Negative indices: count backwards from the top level (e. g.,
-1= top level,-2= one level below the top).
mpy core method:
# 1. Get the object's current index
current_idx = obj.get_index()
# 2. Move to the specified index (e.g., move up 1 level)
obj.move_to_index(current_idx + 1)
# 3. Move directly to the bottom layer (index 0)
obj.move_to_index(0)mpy example:



4.7.2.3 Hierarchy Impact of Changing the Parent Object
When you modify an object's parent container via obj.set_parent (new_parent), the object automatically becomes the topmost child of the new parent container.
# Change btn1's parent to btn2; btn1 becomes the topmost child of btn2
btn1.set_parent(btn2)
4.7.3 Top Layer and System Layer (Top & Sys Layers)
LVGL provides two globally visible special layers for each physical display (shared by all screens, not shared across different displays), which are higher in the hierarchy than all objects on regular screens:
layer_top(top-level layer): located at the topmost layer of the currently active screen (lv.screen_active ());layer_sys(system layer): Located at the topmost level oflayer_top, it is the highest hierarchy of the entire display.
Many beginners are confused about LVGL's layer_top / layer_sys / layer_bottom, and the core reason is that they fail to understand the essential difference between "ordinary screen objects" and "global special layers":
- Common objects (such as buttons and pop-ups) belong to "a specific screen" and will disappear when you switch screens;
- A special layer is a "display-level global layer": no matter which screen you switch to, the content on this layer remains visible at all times, and its hierarchy is fixed to be above / below all regular screens.
显示器最终显示效果 = 最顶层往下叠加
├─ layer_sys(系统层,最顶层)→ 比如鼠标光标,永远在所有内容上面
├─ layer_top(顶级图层)→ 比如全局弹窗、悬浮窗,覆盖所有屏幕
├─ 当前活跃的普通屏幕(屏幕A/屏幕B)→ 普通按钮/标签都在这一层
└─ layer_bottom(底层图层)→ 比如全局背景图,在所有屏幕下面4.7.3.1 layer_top (top-level layer): Globally visible "floating window / modal popup"
Similar to the "floating window" or "system pop-up window" on a mobile phone: no matter which APP (corresponding to a regular screen in LVGL) you switch to, the floating window remains displayed; after "modal mode" is enabled, the underlying content cannot be clicked (for example, a mobile phone pop-up window blocks the operations on the APP).
In the following code, two regular screens that can be switched between each other are created, and a globally visible modal popup is generated on layer_top. This popup is similar to the "system-level popup" on mobile phones: it will not disappear when switching between screens, and will block the interaction of the underlying screen. The buttons on the underlying screen can only be used normally after the popup is closed.
# Initialize
import display_driver
import lvgl as lv
lv.init()
# ===================== Step 1: Create two normal screens (for switching test) =====================
# Screen A: add a button; clicking it switches to screen B
scr_a = lv.obj() # Create normal screen A
btn_a = lv.button(scr_a)
btn_a.set_size(180, 60)
btn_a.set_pos(50, 50)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")
# Screen B: add a button; clicking it switches to screen A
scr_b = lv.obj() # Create normal screen B
btn_b = lv.button(scr_b)
btn_b.set_size(180, 60)
btn_b.set_pos(50, 150)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")
# Bind the screen switching event
def switch_to_b(e):
lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)
def switch_to_a(e):
lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)
# ===================== Step 2: Create a global modal popup with layer_top =====================
# 1. Get the display's top layer (global layer, shared by all screens)
top_layer = lv.layer_top()
# 2. Add a "click absorb" flag to top_layer → implements modal behavior (buttons below cannot be clicked)
# Principle: when the user clicks the screen, the click event is received by top_layer, and widgets on the underlying screen do not get the click event
top_layer.add_flag(lv.obj.FLAG.CLICKABLE)
# 3. Create the popup on top_layer (globally visible, stays regardless of which screen is shown)
popup = lv.obj(top_layer) # The parent object is top_layer, not a normal screen!
popup.set_size(300, 200) # Popup size
popup.center() # Popup centered
# Set popup style: white background, gray border, rounded corners
popup.set_style_bg_color(lv.color_hex(0xFFFFFF), 0) # White background
popup.set_style_border_color(lv.color_hex(0xCCCCCC), 0)# Gray border
popup.set_style_border_width(2, 0) # Border width 2px
popup.set_style_radius(10, 0) # Corner radius 10px
# 4. Add text + close button to the popup
popup_label = lv.label(popup)
popup_label.set_text("Global Modal Popup\n→ Persists across screen switches\n→ Blocks clicks on underlying elements")
popup_label.center()
# Add close button: clicking it removes the modal and closes the popup
close_btn = lv.button(popup)
close_btn.set_size(120, 30)
close_btn.align(lv.ALIGN.BOTTOM_MID, 0, -10) # Popup bottom center
close_label = lv.label(close_btn)
close_label.set_text("Close Popup")
# Event to close the popup: remove click absorption + delete the popup
def close_popup(e):
top_layer.remove_flag(lv.obj.FLAG.CLICKABLE) # Cancel click absorption
popup.delete() # Delete the popup
close_btn.add_event_cb(close_popup, lv.EVENT.CLICKED, None)
# ===================== Step 3: Load the initial screen and run the test =====================
lv.screen_load(scr_a) # Load screen A first
It can be seen that:
- Startup procedure: Screen A is displayed, but it is covered by the popup of
layer_top, and clicking the "Switch to B" button on Screen A has no response (modal blocking); - Test operation: Even if you switch to Screen B via other methods (such as modifying the code), the pop-up window will still be displayed on top of Screen B, and the "Switch to A" button on Screen B will also be unclickable;
- Close the pop-up: Click the "Close Popup" button on the pop-up, and the pop-up will disappear.
layer_topwill no longer absorb click events. At this point, the toggle buttons for Screen A/B can be clicked normally, and the screens can be switched between each other. - Core Verification:
layer_topis a "global" pop-up window: switching between regular screens will not affect it, and it can block all underlying interactions — this is precisely the core logic of a "system-level modal pop-up / floating window" on mobile devices.


4.7.3.2 layer_sys (system layer): The topmost "system-level element"
LVGL internally uses this layer to place elements that "must always be on top"(such as the mouse cursor). Even if layer_top has a pop-up window, layer_sys content will still cover the pop-up.
The demo code is as follows:
# Initialize
import display_driver
import lvgl as lv
import time
lv.init()
# ===================== Step 1: Create two normal screens (for switching test) =====================
# Screen A: add a button; clicking it switches to screen B
scr_a = lv.obj() # Create normal screen A
btn_a = lv.button(scr_a)
btn_a.set_size(180, 60)
btn_a.set_pos(50, 50)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")
# Screen B: add a button; clicking it switches to screen A
scr_b = lv.obj() # Create normal screen B
btn_b = lv.button(scr_b)
btn_b.set_size(180, 60)
btn_b.set_pos(50, 150)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")
# Bind the screen switching event
def switch_to_b(e):
lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)
def switch_to_a(e):
lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)
# ===================== Step 2: Create a global modal popup with layer_top =====================
# 1. Get the display's top layer (global layer, shared by all screens)
top_layer = lv.layer_top()
# 2. Add a "click absorb" flag to top_layer → implements modal behavior (buttons below cannot be clicked)
# Principle: when the user clicks the screen, the click event is received by top_layer, and widgets on the underlying screen do not get the click event
top_layer.add_flag(lv.obj.FLAG.CLICKABLE)
# 3. Create the popup on top_layer (globally visible, stays regardless of which screen is shown)
popup = lv.obj(top_layer) # The parent object is top_layer, not a normal screen!
popup.set_size(300, 200) # Popup size
popup.center() # Popup centered
# Set popup style: white background, gray border, rounded corners
popup.set_style_bg_color(lv.color_hex(0xFFFFFF), 0) # White background
popup.set_style_border_color(lv.color_hex(0xCCCCCC), 0)# Gray border
popup.set_style_border_width(2, 0) # Border width 2px
popup.set_style_radius(10, 0) # Corner radius 10px
# 4. Add text + close button to the popup
popup_label = lv.label(popup)
popup_label.set_text("Global Modal Popup\n→ Persists across screen switches\n→ Blocks clicks on underlying elements")
popup_label.center()
# Add close button: clicking it removes the modal and closes the popup
close_btn = lv.button(popup)
close_btn.set_size(120, 30)
close_btn.align(lv.ALIGN.BOTTOM_MID, 0, -10) # Popup bottom center
close_label = lv.label(close_btn)
close_label.set_text("Close Popup")
# Event to close the popup: remove click absorption + delete the popup
def close_popup(e):
top_layer.remove_flag(lv.obj.FLAG.CLICKABLE) # Cancel click absorption
popup.delete() # Delete the popup
close_btn.add_event_cb(close_popup, lv.EVENT.CLICKED, None)
# ===================== Step 3: Load the initial screen and run the test =====================
lv.screen_load(scr_a) # Load screen A first
# Get the system layer (topmost layer)
sys_layer = lv.layer_sys()
# 2. Create a small circle (simulates a mouse cursor)
cursor = lv.obj(sys_layer)
cursor.set_size(20, 20) # Cursor size 20x20
cursor.set_style_bg_color(lv.color_hex(0xFF0000), 0) # Red background
cursor.set_style_radius(10, 0) # Circle (radius = size/2)
After running, you can see the following:
As we run the command to adjust the ball position in the REPL, the red circular cursor will pass through the pop-up window of layer_top and always stay on top (the cursor remains visible even when blocked by the pop-up).
The summary is as follows:
layer_sysis the "ultimate top layer", and no content can override it;- Developers generally do not use
layer_systo avoid interfering with the internal cursor/system elements of LVGL; - Each display has its own
layer_sys, which is not shared between different displays.
4.7.4 layer_bottom (bottom layer): Global background image
Set the "background for all screen shares", such as the global background image of an APP, so that the background remains unchanged no matter which page (screen) you switch to (provided that the screen background is semi-transparent).
In the following code, we set:
- layer_bottom refers to the dark blue global background;
- Screen A features a light gray semi-transparent background;
- Screen B has a background of a different color.
# Initialize
import display_driver
import lvgl as lv
import time
lv.init()
# ===================== Step 1: Create the global background for layer_bottom =====================
# Get the bottom layer
bottom_layer = lv.layer_bottom()
# Global background: dark blue (#1A237E), fully opaque (to highlight the global background)
bg_rect = lv.obj(bottom_layer)
bg_rect.set_size(lv.pct(80), lv.pct(80)) # Fill the entire screen
bg_rect.set_style_bg_color(lv.color_hex(0x1A237E), 0) # Dark blue (high contrast)
bg_rect.set_style_bg_opa(255, 0) # Background opaque
# ===================== Step 2: Create two normal screens (semi-transparent background) =====================
# Screen A: semi-transparent background (so the light cyan of the bottom layer shows through)
scr_a = lv.obj()
scr_a.set_style_bg_opa(64, 0) # Opacity 64 (25%), more transparent
scr_a.set_style_bg_color(lv.color_hex(0xF5F5F5), 0) # Light gray
btn_a = lv.button(scr_a)
btn_a.set_pos(50, 50)
btn_a.set_size(180, 60)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")
# Screen B: semi-transparent background as well
scr_b = lv.obj()
scr_b.set_style_bg_opa(64, 0)
scr_b.set_style_bg_color(lv.color_hex(0xF5F5F5), 0)
btn_b = lv.button(scr_b)
btn_b.set_pos(50, 150)
btn_b.set_size(180, 60)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")
# Bind the switch event
def switch_to_b(e):
lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)
def switch_to_a(e):
lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)
# ===================== Step 3: Test the result =====================
lv.screen_load(scr_a)


It can be seen that when switching between screen A and screen B, the dark blue global background remains unchanged all the time, while the light gray screen background changes accordingly with the switching.
Version Record
Version Number | Modifier | Time | Content |
v1.0 | Li Zisheng | 2026/03/24 | Initialize the document. |
v1.1 | Li Zisheng | 2026/03/24 | Add layer management articles. |