Labs / LVGL

03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

Author: Li Zisheng · Source: FreakStudio open documentation, v1.0 · License: CC BY 4.0

Contents

0. Environment Preparation

Note: The simulator only supports versions related to v9.0:

v9.0

Simulator Address: https://sim.lvgl.io/v9.0/micropython/ports/webassembly

v9.0

Reference code address: https://docs.lvgl.io/9.0/examples.html

1. Hello World

1.1 Brief Introduction to API

MicroPython APIFunction descriptionUsage example
lv.init()Initialize the LVGL core enginelv.init()
lv.screen_active()Get the system default active screenscr = lv.screen_active()
lv.color_hex(hex_val)Generate a color value in hexadecimal RGB formatlv.color_hex(0x003a57) / lv.color_hex(0xffffff)
obj.set_style_bg_color(color, part)Set the object background color (the main part PART.MAIN must be specified)scr.set_style_bg_color(lv.color_hex(0x003a57), lv.PART.MAIN)
lv.label(parent)Create a label widget (bound to the specified parent object)label = lv.label(scr)
label.set_text(text)Set the text displayed by the labellabel.set_text("Hello world")
obj.set_style_text_color(color, part)Set the object text color (the main part PART.MAIN must be specified)scr.set_style_text_color(lv.color_hex(0xffffff), lv.PART.MAIN)
obj.align(align, x_off, y_off)Set widget alignment (x/y are offsets)label.align(lv.ALIGN.CENTER, 0, 0)
lv.screen_load(scr)Load the specified screen as the currently displayed screenlv.screen_load(scr)

1.2 Sample Code

import display_driver
import lvgl as lv

lv.init()

# 1. Get the current active screen (replaces `scr = lv.obj()` in the original template; corresponds to `lv_screen_active()` in C)
scr = lv.screen_active()

# 2. Set the screen background color to 0x003a57 (dark blue); corresponds to `lv_obj_set_style_bg_color` in C
scr.set_style_bg_color(lv.color_hex(0x003a57), lv.PART.MAIN)

# 3. Create a label (parent object is the active screen)
label = lv.label(scr)
label.set_text("Hello world")

# 4. Set the screen's text color to white (0xffffff); corresponds to `lv_obj_set_style_text_color` in C
scr.set_style_text_color(lv.color_hex(0xffffff), lv.PART.MAIN)

# 5. Center-align the label (same as the original template)
label.align(lv.ALIGN.CENTER, 0, 0)

# 6. Load the screen (this step is required in the simulator for the interface to display)
lv.screen_load(scr)
v9.0
v9.0

1.3 Usage Notes

2. Buttons

2.1 Brief Introduction to API

MicroPython APIFunction descriptionUsage example
lv.init()Initialize the LVGL core enginelv.init()
lv.screen_active()Get the system default active screenscr = lv.screen_active()
lv.button(parent)Create a button widget (bound to the specified parent object)btn = lv.button(scr)
obj.set_pos(x, y)Set the widget's coordinate position (x/y are coordinates relative to the parent object)btn.set_pos(10, 10)
obj.set_size(width, height)Set the widget's width and heightbtn.set_size(120, 50)
obj.add_event_cb(cb, event, user_data)Register a callback function for the specified event type on the widgetbtn.add_event_cb(btn_event_cb, lv.EVENT.PRESSED, None)
lv.label(parent)Create a label widget (bound to the specified parent object)label = lv.label(btn)
label.set_text(text)Set the text displayed by the labellabel.set_text("Button")
obj.center()Center the widget within its parent objectlabel.center()
lv.screen_load(scr)Load the specified screen as the currently displayed screenlv.screen_load(scr)

2.2 Sample Code

import display_driver
import lvgl as lv

lv.init()

# 1. Get the currently active screen object (corresponds to lv_screen_active() in C)
scr = lv.screen_active()

# 2. Create a button (corresponds to lv_button_create(lv_screen_active()) in C)
btn = lv.button(scr)

# 3. Set the button position (x=10, y=10) (corresponds to lv_obj_set_pos(btn, 10, 10) in C)
btn.set_pos(10, 10)

# 4. Set the button size (width 120, height 50) (corresponds to lv_obj_set_size(btn, 120, 50) in C)
btn.set_size(120, 50)

# 5. Define the button interaction callback function (corresponds to btn_event_cb in C)
def btn_event_cb(e):  
    print("Button clicked!")

# 6. Register the button interaction callback function
btn.add_event_cb(btn_event_cb, lv.EVENT.PRESSED, None) 

# 7. Create the label inside the button (corresponds to lv_label_create(btn) in C)
label = lv.label(btn)

# 8. Set the label text (corresponds to lv_label_set_text(label, "Button") in C)
label.set_text("Button")

# 9. Center the label inside the button (corresponds to lv_obj_center(label) in C)
label.center()

# 10. Load the screen (this step is required in the simulator for the interface to display)
lv.screen_load(scr)
v9.0
v9.0
v9.0

First initialize the LVGL core engine, obtain the currently active screen object, then create a 120×50 sized button at the top-left corner of the screen (coordinates 10,10), register a press event callback function for the button (which prints "Button clicked!" to the Console when pressed), create a label displaying the text "Button" centered inside the button, and finally load the screen to complete the interface rendering.

2.3 Usage Notes

Version Record

Version Number

Modifier

Time

Content

v1.0

Li Zisheng

2026/03/23

Initialize the document.

3. Matrix Keypad

Sample Code:

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 a button matrix
btnm = lv.buttonmatrix(scr)
#Set 3 buttons
btnm_map = ["A1", "A2", "A3"]
btnm.set_map(btnm_map)
#Center it
btnm.center()

#Interaction callback function
def btnm_event_cb(e):
    #Get the index of the clicked button
    pressed_btn = btnm.get_selected_button()  
    if pressed_btn != -1:
        #Get the text of the button at the corresponding index
        text_btn = btnm.get_button_text(pressed_btn)
        print(f"Button {text_btn} is clicked")  # Only this line is modified, output in English only
#Register the interaction callback function. For more states see the "class EVENT" section of api.py
btnm.add_event_cb(btnm_event_cb, lv.EVENT.CLICKED, None)

# Load the screen
lv.screen_load(scr)
A1 A2 A3
v9.0 A1 A2 A3

First, initialize the LVGL core engine, obtain the currently active screen object and set its background color to black. Next, create a matrix button control containing three buttons "A1", "A2" and "A3" and make it displayed centered on the screen. Bind a click event callback function to this matrix button: when any button is clicked, acquire the index and corresponding text of the clicked button, and print a fully English button click prompt in the Console (e. g., "Button A1 is clicked"). Finally, load the screen to complete the rendering of the entire interface.

IV. Basic Objects

The following code implements a rectangular control with a custom visual style: 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 semi-transparent shadow for this object, and finally load the screen to complete the rendering, and a red square with green border and shadow will be displayed on the screen in the end.

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)
v9.0
4.3

4.1 Modify the screen background color

#Set the screen background color to black
scr.set_style_bg_color(lv.color_hex(0x09999), 0)
4.2

4.2 Modify the position and size of the 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
v9.0 4.3

4.3 Modify Padding

Padding refers to the space between the "inner content area" and the "border" of a control, similar to the gap reserved between an item inside a box and the inner wall of the box. The larger the padding, the farther the content is from the border.

Next, we will add a Label object to the base object; the Label will be displayed inside the red square obj rather than directly on the screen. After that, we will try adjusting the padding and set the Label to be centered:

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(0x009999), 0)

#Create the object
obj = lv.obj(scr)
#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

#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(20)   #Set left padding
# style_obj .set_pad_right(5)  #Set right padding
# style_obj .set_pad_top(8)    #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)

# 1. Create a Label widget with obj as the parent (the Label is displayed inside obj)
label = lv.label(obj)
# 2. Set the text displayed by the Label
label.set_text("Test Label")
# 3. Center the Label inside obj (using the blank area left by the padding)
label.center()
# 4. Optional: set the text color to white (clearer on a red background)
label.set_style_text_color(lv.color_hex(0x11111), lv.STATE.DEFAULT)

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

Next, let's modify the padding:

#Border and background
# style_obj .set_pad_all(10)    #Set padding in all four directions
style_obj  .set_pad_left(20)   #Set left padding
style_obj .set_pad_right(1)  #Set right padding
style_obj .set_pad_top(1)    #Set top padding
style_obj  .set_pad_bottom(30) #Set bottom padding

Displayed as follows:

03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

4.4 Modify Transparency

style_obj .set_bg_opa(100)  #Set background opacity; 0 is fully transparent
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

4.4 Modify Background Color

style_obj .set_bg_color(lv.color_hex(0x000000))   #Set background color
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

4.5 Modify Border Color

style_obj .set_border_color(lv.color_hex(0x00FFFF))   #Set border color
v9.0

4.6 Modify Border Width

style_obj  .set_border_width(5)   #Set border width
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

4.7 Modify Border Opacity

style_obj .set_border_opa(160)   #Set border opacity; 0 is fully transparent
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

4.8 Modify Shadow Width, Opacity and Offset

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(0x009999), 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(100)#Set shadow width (shadow spread range)
style_obj .set_shadow_opa(250)#Set shadow opacity
style_obj .set_shadow_offset_x(50)#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)
v9.0

5. Labels

The following code implements a red scrolling text effect on a black background:

  1. First initialize the LVGL engine and set the screen background to solid black;
  2. Next, create a label control, configure it with the "circular scrolling" long text display mode (to adapt to scenarios where the text length exceeds the label size), set the label size to 100×20 pixels, set the display text to "HELLO MicroPython LVGL", and make the label display in the center of the screen;
  3. Then create a custom style, set the text color to red, the font to 16-point Montserrat, and apply this style to the default state of the label; finally, the loading screen finishes rendering, and the final effect is that the red text in the center of the black screen scrolls continuously in a marquee loop.
v9.0
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 a label
label = lv.label(scr)
#Set the long-text display mode. For more parameters see the "class LONG_MODE" section of api.py
label.set_long_mode(lv.label.LONG.SCROLL_CIRCULAR) 
# Set the label size (must be smaller than the text length to trigger scrolling)
label.set_size(100, 20)
# Set the text content
label.set_text("HELLO MicroPython LVGL")
# Center the label
label.align(lv.ALIGN.CENTER, 0, 0)

##Create a style. For more APIs see the "class style_t" section of api.py
style_label = lv.style_t()     
#Text color
style_label.set_text_color(lv.color_hex(0xFF0000))  
#Set the font; supports 12, 14, 16
style_label.set_text_font(lv.font_montserrat_16)
#Apply as the default state style. For more states see the "class STATE" section of api.py
label.add_style(style_label , lv.STATE.DEFAULT)

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

5.1 Modify Different Long Text Display Modes

5.1.1 WRAP (Word Wrap Mode)

When the text length exceeds the label width, it will automatically wrap to the next line to fully display all text content (no clipping or scrolling).

label.set_long_mode(lv.label.LONG.WRAP) 
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

5.1.2 SCROLL Springback Scroll Mode

When the text length exceeds the label width, it will scroll cyclically according to the following rules:

  1. Step 1 (Left Shift): The text starts from its initial position and scrolls left until the end of the text is fully displayed within the tag (reaching the leftmost end);
  2. Step 2 (Shift Right): Then it will automatically scroll rightward to return to the initial position of the text (shift right back to the starting point);
  3. Looping back and forth: After that, the process of "shifting left to the end → shifting right back to the starting point" will be repeated continuously, creating a "scrolling back and forth" effect.
label.set_long_mode(lv.label.LONG.SCROLL) 
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

5.1.3 DOT (Ellipsis Mode)

When the text length exceeds the label width, an ellipsis (. ..) will be displayed at the end, indicating that there is still undisplayed content, with no line wrapping or scrolling.

label.set_long_mode(lv.label.LONG.DOT) 
label.set_size(100, 50)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

5.1.4 CLIP (Cropping Mode)

When the text length exceeds the label width, the excess part will be directly cropped without displaying any additional marks (such as an ellipsis), and the excess part will be completely invisible.

label.set_long_mode(lv.label.LONG.CLIP) 
label.set_size(100, 50)
5.2

5.2 Set Font

First, run the following code, which will print out all the font names built into LVGL, and these names are directly available for use:

import display_driver
import lvgl as lv

lv.init()

# Print all attributes starting with "font_" (i.e. all built-in fonts)
font_list = [attr for attr in dir(lv) if attr.startswith("font_")]
print("可用字体列表:", font_list)
font_montserrat_14 font_montserrat_16 font_montserrat_24
style_label.set_text_font(lv.font_montserrat_14)
5.2
style_label.set_text_font(lv.font_montserrat_24)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

5.3 Set Font Color

03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)
Color nameHexadecimal valueCode syntaxEffect
Pure black0x000000lv.color_hex(0x000000)Screen background color
Pure white0xFFFFFFlv.color_hex(0xFFFFFF)Most eye-catching on a black background
Pure red0xFF0000lv.color_hex(0xFF0000)The text color you used before
Pure green0x00FF00lv.color_hex(0x00FF00)Commonly used for highlight prompts
Pure blue0x0000FFlv.color_hex(0x0000FF)Commonly used for links / emphasized text
Yellow0xFFFF00lv.color_hex(0xFFFF00)Commonly used for warning messages
Purple0xFF00FFlv.color_hex(0xFF00FF)Decorative text
Cyan0x00FFFFlv.color_hex(0x00FFFF)Fresh highlight color
Dark gray0x333333lv.color_hex(0x333333)Secondary text background
Light gray0xEEEEEElv.color_hex(0xEEEEEE)Light-colored text
Orange0xFF9900lv.color_hex(0xFF9900)Commonly used for tips

6. Switches

The following code implements an interactive switch control on a black background, whose core function is to respond to switch state changes in real time and output corresponding prompts:

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 a switch
switch = lv.switch(scr)
#Set the size
switch.set_size(100, 50)
#Center it
switch.center()

#Interaction callback function
def switch_event_cb(e):
    if switch.has_state(lv.STATE.CHECKED):
        print("OPEN")
    else:
        print("CLOSE")
#Register the interaction callback function. For more states see the "class EVENT" section of api.py
switch.add_event_cb(switch_event_cb, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)
v9.0 v1.20.0-1053-g349ae32bf-dirty 2024-09-11
v9.0

In the code above:

6.1 Switch Linkage Label (Control Text Display / Color)

Added a label control that synchronously modifies the label text and color when the switch toggles, achieving "control linkage".

import display_driver
import lvgl as lv

lv.init()

scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create a switch
switch = lv.switch(scr)
switch.set_size(100, 50)
switch.align(lv.ALIGN.CENTER, 0, -40)  # Move up to leave room for the label

# ========== New: create the linked label ==========
label = lv.label(scr)
label.set_text("Switch is CLOSE")
label.align(lv.ALIGN.CENTER, 0, 20)
# Label style (initially red)
style_label = lv.style_t()
style_label.init()
style_label.set_text_color(lv.color_hex(0xFF0000))
label.add_style(style_label, lv.STATE.DEFAULT)

# Modified callback: linked label
def switch_event_cb(e):
    if switch.has_state(lv.STATE.CHECKED):
        print("OPEN")
        label.set_text("Switch is OPEN")
        label.set_style_text_color(lv.color_hex(0x00FF00), lv.STATE.DEFAULT)  # Green
    else:
        print("CLOSE")
        label.set_text("Switch is CLOSE")
        label.set_style_text_color(lv.color_hex(0xFF0000), lv.STATE.DEFAULT)  # Red

switch.add_event_cb(switch_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0
v9.0

6.2 Complete Switch Configuration (Styles of Track and Slider)

The following code implements a switch control with customizable style, precise centering and interactive feedback on a black background:

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 and initialize the style object
style_switch = lv.style_t()
style_switch.init()

#Create a switch
switch = lv.switch(scr)
#Set the size
switch.set_size(100, 50)

# First remove all default styles
switch.remove_style_all()

# Off state + track (main part): dark gray
switch.set_style_bg_color(lv.color_hex(0x444444), lv.STATE.DEFAULT | lv.PART.MAIN)
switch.set_style_bg_opa(255, lv.STATE.DEFAULT | lv.PART.MAIN)  # Opaque
switch.set_style_radius(25, lv.STATE.DEFAULT | lv.PART.MAIN)   # Rounded corners
switch.set_style_border_width(0, lv.STATE.DEFAULT | lv.PART.MAIN)  # Remove the default border

# On state + track (main part): green
switch.set_style_bg_color(lv.color_hex(0x00FF00), lv.STATE.CHECKED | lv.PART.MAIN)
switch.set_style_bg_opa(255, lv.STATE.CHECKED | lv.PART.MAIN)
switch.set_style_radius(25, lv.STATE.CHECKED | lv.PART.MAIN)
switch.set_style_border_width(0, lv.STATE.CHECKED | lv.PART.MAIN)

# Off state knob: white
switch.set_style_bg_color(lv.color_hex(0xFFFFFF), lv.STATE.DEFAULT | lv.PART.KNOB)
switch.set_style_bg_opa(255, lv.STATE.DEFAULT | lv.PART.KNOB)
switch.set_style_radius(25, lv.STATE.DEFAULT | lv.PART.KNOB)  # Round knob

# On state knob: yellow
switch.set_style_bg_color(lv.color_hex(0xFFFF00), lv.STATE.CHECKED | lv.PART.KNOB)
switch.set_style_bg_opa(255, lv.STATE.CHECKED | lv.PART.KNOB)
switch.set_style_radius(25, lv.STATE.CHECKED | lv.PART.KNOB)

# Center it
switch.center() 

#Interaction callback function
def switch_event_cb(e):
    if switch.has_state(lv.STATE.CHECKED):
        print("OPEN")
    else:
        print("CLOSE")

#Register the interaction callback function. For more states see the "class EVENT" section of api.py
switch.add_event_cb(switch_event_cb, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)
255 25px
v9.0 0x00FF00 0xFFFF00

The core logic for customizing the styled state of the switch (track + slider) is as follows:

After all style and size settings are completed, call switch.center (): to recalculate the centering coordinates based on the switch's final style and size state, so as to avoid position offset caused by premature centering and ensure that the switch is accurately displayed in the exact center of the screen.

7. Indicator Light LED

In the following code, we create an LED indicator:

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 an LED
led = lv.led(scr)
#Set the size
led.set_size(50, 50)
#Set the color when lit
led.set_color(lv.color_hex(0xFF0000))
# Set the brightness; range: 0-255
led.set_brightness(150)  
#Center it
led.center()

#Turn on
#led.on()
#Turn off
#led.off()
# Toggle the state
#led.toggle() 

# Load the screen
lv.screen_load(scr)
v9.0

7.1 Multi-Color Water Flowing Lights with Automatic Brightness Adjustment

Create 4 LED lights of different colors to realize the functions of "sequential flowing lighting + automatic brightness gradient":

import display_driver
import lvgl as lv

lv.init()

# 1. Screen configuration: black background
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# 2. Create 4 LEDs, arranged horizontally
led_list = []
led_colors = [
    lv.color_hex(0xFF0000),   # Red
    lv.color_hex(0x00FF00),   # Green
    lv.color_hex(0x0000FF),   # Blue
    lv.color_hex(0xFFFF00)    # Yellow
]
# Create 4 LEDs in a loop, arranged horizontally
for i in range(4):
    led = lv.led(scr)
    led.set_size(50, 50)  # LED size
    # Horizontal layout: centered on the screen, x-axis offsets of ±80/±20
    x_offset = -100 + i * 60
    led.align(lv.ALIGN.CENTER, x_offset, 0)
    led.set_color(led_colors[i])  # Set different colors
    led_list.append(led)

# 3. Running-light control variables
current_led_idx = 0    # Index of the currently lit LED
brightness = 0         # Current brightness (0-255)
brightness_dir = 1     # Brightness change direction: 1 = increasing, -1 = decreasing

# 4. Timer callback: automatically adjust brightness + switch running light
def flow_led_timer_cb(e):
    global current_led_idx, brightness, brightness_dir
    
    # Step 1: turn off all LEDs first
    for led in led_list:
        led.off()
    
    # Step 2: adjust brightness (0→255→0 back and forth)
    brightness += brightness_dir * 5  # Changes by 5 each time; speed is adjustable
    if brightness >= 255:
        brightness = 255
        brightness_dir = -1  # Maximum value reached, start decreasing
    elif brightness <= 0:
        brightness = 0
        brightness_dir = 1   # Minimum value reached, start increasing
    
    # Step 3: light the current LED and set its brightness
    current_led = led_list[current_led_idx]
    current_led.on()
    current_led.set_brightness(brightness)
    print(f"LED ID:{current_led_idx+1}, brightness:{brightness}")
    
    # Step 4: switch to the next LED (looping)
    current_led_idx = (current_led_idx + 1) % len(led_list)

# Create a timer: run the callback every 100ms (running-light speed)
lv.timer_create(flow_led_timer_cb, 100, None)

# Load the screen
lv.screen_load(scr)
90 95 100

7.2 Switch Control for LED On/Off

import display_driver
import lvgl as lv
import time

lv.init()

scr = lv.screen_active()
# Black background
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

switch = lv.switch(scr)
# Switch size
switch.set_size(100, 50)  
# Call center to ensure accurate positioning
switch.center()

# Initialize with the given LED class, parent object is the screen
led1 = lv.led(scr)  
# LED size
led1.set_size(80, 80)  
# Place the LED 80 pixels below the switch
led1.align(lv.ALIGN.CENTER, 0, 80)  
# Set the LED color to red
led1.set_color(lv.color_hex(0xFF0000))
# Full brightness (0-255)
led1.set_brightness(255)  

# Bind the switch to the LED control logic
def switch_led_cb(e):
    if switch.has_state(lv.STATE.CHECKED):
        led1.on()  # Switch on → LED on
        print("LED ON (Red)")
    else:
        led1.off()  # Switch off → LED off
        print("LED OFF")

# Bind the switch value-changed event
switch.add_event_cb(switch_led_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0
v9.0

8. Checkbox

The following code implements an interactive checkbox control that is centered on a black background. Its core function is to respond to the checked / unchecked state of the checkbox in real time and output corresponding prompts to the Console.

import display_driver
import lvgl as lv
import time

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 a checkbox
cb = lv.checkbox(scr)
#Set the checkbox text
cb.set_text("checkbox")  
#Center it
cb.center()

#Interaction callback function
def cb_event_cb(e):
    if cb.has_state(lv.STATE.CHECKED):
        print("choose")
    else:
        print("not choose")
#Register the interaction callback function. For more states see the "class EVENT" section of api.py
cb.add_event_cb(cb_event_cb, lv.EVENT.VALUE_CHANGED, None) 

lv.screen_load(scr)
v9.0 8.1
v9.0 8.2 v1.20.0

8.1 Checkbox Font Customization Display

The following code creates a check box and customizes its text style (font, color, size):

import display_driver
import lvgl as lv
import time

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(0xFFFFFF), 0)

#Create a checkbox
cb = lv.checkbox(scr)
#Set the checkbox text
cb.set_text("checkbox")  
#Center it
cb.center()

# Create a font style object
style_cb_text = lv.style_t()
style_cb_text.init()
# Set the font
style_cb_text.set_text_font(lv.font_montserrat_24)
# Apply the style to the checkbox
cb.add_style(style_cb_text, lv.STATE.DEFAULT)

#Interaction callback function
def cb_event_cb(e):
    global cb_text
    cb_text = cb.get_text()
    if cb.has_state(lv.STATE.CHECKED):
        print(f"choose|text : {cb_text}")
    else:
        print(f"not choose|text : {cb_text}")
#Register the interaction callback function. For more states see the "class EVENT" section of api.py
cb.add_event_cb(cb_event_cb, lv.EVENT.VALUE_CHANGED, None) 

lv.screen_load(scr)
8.1
8.1

8.2 Control the LED by checking the checkbox

In the following code, tick the checkbox to turn on the LED:

import display_driver
import lvgl as lv

lv.init()

# Screen initialization (keep the white background from your original code)
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# 1. Minimal checkbox (no extra styling, get it running first)
cb = lv.checkbox(scr)
cb.set_text("Test LED")
cb.center()

# 2. Minimal LED (only set size + color + position, no dependence on checkbox alignment)
led = lv.led(scr)
led.set_size(50, 50)
led.align(lv.ALIGN.CENTER, 0, 60)  # Directly below the checkbox
led.set_color(lv.color_hex(0xFF0000))

# 3. Minimal callback (only controls the LED on/off, no global variables)
def cb_test_cb(e):
    if cb.has_state(lv.STATE.CHECKED):
        led.on()
        print("choose")
    else:
        led.off()
        print("not choose")

# 4. Register the event (format identical to your original code)
cb.add_event_cb(cb_test_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0 8.2
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

IX. Arc

The following code implements an interactive Arc control centered on a white background, whose core function is to update and display/print its current value in real time when the arc is dragged:

import display_driver
import lvgl as lv

lv.init()

# Screen initialization (keep the white background from your original code)
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

#Create an arc
arc = lv.arc(scr)
#Set the arc size
arc.set_size(150, 150)
#Set the arc value range
arc.set_range(0, 100)
#Set the current value
arc.set_value(10)
#Center it
arc.center()

# Create a value display label
lbl_val = lv.label(scr)
lbl_val.set_text(str(arc.get_value()))
lbl_val.align(lv.ALIGN.CENTER, 0, 0)

#Interaction callback function
def arc_event_cb(e):
    current_val = arc.get_value()
    lbl_val.set_text(str(current_val))
    print(current_val)

#Register the interaction callback function
arc.add_event_cb(arc_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0 10
v9.0 29
v9.0 83 30

9.1 Setting Dimensions and Value Ranges

import display_driver
import lvgl as lv

lv.init()

# Screen initialization (keep the white background from your original code)
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

#Create an arc
arc = lv.arc(scr)
#Set the arc size
arc.set_size(200, 200)
#Set the arc value range
arc.set_range(0, 360)
#Set the current value
arc.set_value(10)
#Center it
arc.center()

# Create a value display label
lbl_val = lv.label(scr)
lbl_val.set_text(str(arc.get_value()))
lbl_val.align(lv.ALIGN.CENTER, 0, 0)

#Interaction callback function
def arc_event_cb(e):
    current_val = arc.get_value()
    lbl_val.set_text(str(current_val))
    print(current_val)

#Register the interaction callback function
arc.add_event_cb(arc_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0 328

9.2 Adjustment Mode

arc.set_mode(lv.arc.MODE.REVERSE) # MODE.REVERSE: reverse expansion, suitable for "countdown, reverse adjustment" scenarios
v9.0 274
arc.set_mode(lv.arc.MODE.SYMMETRICAL) # MODE.SYMMETRICAL: values are symmetric about the middle value (set a positive/negative range)
# Suitable for "temperature ±, volume balance" scenarios
262 9.5

9.3 Set Background Arc

import display_driver
import lvgl as lv

lv.init()

# Screen initialization (keep the white background from your original code)
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

#Create an arc
arc = lv.arc(scr)
#Set the arc size
arc.set_size(200, 200)
#Set the arc value range
arc.set_range(0, 360)
#Set the current value
arc.set_value(10)
#Center it
arc.center()

# Set the mode
arc.set_mode(lv.arc.MODE.NORMAL) # MODE.NORMAL: most common, value goes from minimum → maximum, arc expands clockwise

#  Set the background arc
arc.set_bg_angles(0, 270)

# Create a value display label
lbl_val = lv.label(scr)
lbl_val.set_text(str(arc.get_value()))
lbl_val.align(lv.ALIGN.CENTER, 0, 0)

#Interaction callback function
def arc_event_cb(e):
    current_val = arc.get_value()
    lbl_val.set_text(str(current_val))
    print(current_val)

#Register the interaction callback function
arc.add_event_cb(arc_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
240

9.4 Arc Integral Rotation

# The whole arc widget spans 90 degrees
arc.set_rotation(90)
264

9.5 Curve Control of LED Brightness

The code is as follows:

import display_driver
import lvgl as lv

lv.init()

# 1. Screen initialization
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# 2. Create the arc (integrating the core methods)
arc = lv.arc(scr)
arc.set_size(150, 150)
# Display a full circle
arc.set_angles(0, 360)        
arc.set_bg_angles(0, 360)

# Value range = LED brightness range (0~255)
arc.set_range(0, 255)         
# Initial brightness 0 (LED off)
arc.set_value(0)              
# Normal mode (clockwise to brighten)
arc.set_mode(lv.arc.MODE.NORMAL)  
# Centered in the upper half of the screen
arc.align(lv.ALIGN.CENTER, 0, -50)  

# 3. Create the LED
led = lv.led(scr)
led.set_size(80, 80)
led.align(lv.ALIGN.CENTER, 0, 80)  # Centered below the arc
led.set_color(lv.color_hex(0xFF0000))  # Red LED
led.set_brightness(0)  # Initial brightness 0

# 4. Interaction callback: arc value → LED brightness
def arc_led_cb(e):
    # get_value: get the current value of the arc (0~255)
    brightness = arc.get_value()
    # Set the LED brightness
    led.set_brightness(brightness)
    # Print for debugging (value = brightness)
    print(f"LED Brightness : {brightness}")

# Bind the value-changed event
arc.add_event_cb(arc_led_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0

X. Slider

The code is as follows:

import display_driver
import lvgl as lv

lv.init()

# Screen initialization
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

#Create a slider
slider = lv.slider(scr)
#Set the slider size
slider.set_size(300, 50)
#Set the slider value range
slider.set_range(0, 100)
#Center it
slider.center()

#Create a value display label
lbl_val = lv.label(scr)
lbl_val.set_text(str(slider.get_value()))
lbl_val.align(lv.ALIGN.CENTER, 0, -50)

#Interaction callback function
def slider_event_cb(e):
    current_val = slider.get_value()
    lbl_val.set_text(str(current_val))
    print(current_val)
    
#Register the interaction callback function. For more states see the "class EVENT" section of api.py
slider.add_event_cb(slider_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
v9.0 55

10.1 Modify Slider Mode

The differences between the different modes are as follows:

ConstantPurpose
NORMALNormal mode (default): single slider, dragged from the minimum value to the maximum value (this is what your earlier code used)
SYMMETRICALSymmetric mode: centered on 0, with values symmetric about zero (for example, with a range of -50 to 50, the slider at center is 0)
RANGERange mode: dual sliders, lets you select a value interval (for example, setting a range of 10 to 80)

10.1.1 Scope Mode

The code is as follows:

import display_driver
import lvgl as lv

lv.init()

# Screen initialization
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# ===================== Core change: slider mode =====================
# Create the slider and set it to [RANGE mode] (dual knobs)
slider = lv.slider(scr)
slider.set_mode(lv.slider.MODE.RANGE)  # Switch to range mode
# You can also try symmetrical mode: slider.set_mode(lv.slider.MODE.SYMMETRICAL)

# Set the slider size (keep width > height for horizontal mode)
slider.set_size(300, 50)
# Symmetrical mode: set a symmetric range (e.g. -50~50); range mode can use 0~100
slider.set_range(0, 100)
slider.center()

# ===================== Label display adapted to the mode =====================
# Main knob value label (right knob)
lbl_main = lv.label(scr)
lbl_main.set_text(f"main value:{slider.get_value()}")
lbl_main.align(lv.ALIGN.CENTER, 0, -50)

# Added for range mode: left knob value label
lbl_left = lv.label(scr)
lbl_left.set_text(f"left value:{slider.get_left_value()}")
lbl_left.align(lv.ALIGN.CENTER, 0, -80)

# ===================== Callback function adapted to multiple modes =====================
def slider_event_cb(e):
    # Get the values of the main knob (right) and the left knob
    main_val = slider.get_value()
    left_val = slider.get_left_value()
    
    # Update the label text
    lbl_main.set_text(f"main value:{main_val}")
    lbl_left.set_text(f"left value:{left_val}")
    
    # Print the mode and values (for debugging)
    print(f"current mode:{slider.get_mode()}, left value:{left_val}, main value:{main_val}")

# Register the value-changed event
slider.add_event_cb(slider_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
18 71 10.1
0 10.1.1

First click once, then drag:

0 41 10.1.1

10.1.2 Symmetric Mode

import display_driver
import lvgl as lv

lv.init()

# Screen initialization
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# ===================== Core change: slider mode =====================
# Create the slider and set it to [RANGE mode] (dual knobs)
slider = lv.slider(scr)
# slider.set_mode(lv.slider.MODE.RANGE)  # Switch to range mode
slider.set_mode(lv.slider.MODE.SYMMETRICAL) # Symmetrical mode

# Set the slider size (keep width > height for horizontal mode)
slider.set_size(300, 50)
# Symmetrical mode: set a symmetric range (e.g. -50~50); range mode can use 0~100
slider.set_range(-50, 50)
slider.center()

# ===================== Label display adapted to the mode =====================
# Main knob value label (right knob)
lbl_main = lv.label(scr)
lbl_main.set_text(f"main value:{slider.get_value()}")
lbl_main.align(lv.ALIGN.CENTER, 0, -50)

# Added for range mode: left knob value label
lbl_left = lv.label(scr)
lbl_left.set_text(f"left value:{slider.get_left_value()}")
lbl_left.align(lv.ALIGN.CENTER, 0, -80)

# ===================== Callback function adapted to multiple modes =====================
def slider_event_cb(e):
    # Get the values of the main knob (right) and the left knob
    main_val = slider.get_value()
    left_val = slider.get_left_value()
    
    # Update the label text
    lbl_main.set_text(f"main value:{main_val}")
    lbl_left.set_text(f"left value:{left_val}")
    
    # Print the mode and values (for debugging)
    print(f"current mode:{slider.get_mode()}, left value:{left_val}, main value:{main_val}")

# Register the value-changed event
slider.add_event_cb(slider_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
50 32 1 10.1.2

10.2 Modify Slider Direction

The following code is not runnable in version 9.0:

Change the slider from the default horizontal (HORIZONTAL) to vertical (VERTICAL), and adjust its size and layout to adapt to the vertical orientation.

import display_driver
import lvgl as lv

lv.init()

# Screen initialization
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# ===================== Core change: slider orientation =====================
slider = lv.slider(scr)
# Force vertical orientation (default is horizontal)
slider.set_orientation(lv.slider.ORIENTATION.VERTICAL)

# Vertical slider: swap width and height (narrow and tall)
slider.set_size(50, 300)  # Width 50, height 300 (vertical orientation needs height > width)
slider.set_range(0, 100)
slider.center()

# ===================== Label layout adapted to vertical orientation =====================
lbl_val = lv.label(scr)
lbl_val.set_text(str(slider.get_value()))
# Place the label to the right of the vertical slider (X offset +80, Y centered)
lbl_val.align(lv.ALIGN.CENTER, 80, 0)

# ===================== Callback function (logic unchanged, layout adapted) =====================
def slider_event_cb(e):
    current_val = slider.get_value()
    lbl_val.set_text(f"当前值:{current_val}")
    print(f"垂直滑动条值:{current_val}")

slider.add_event_cb(slider_event_cb, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)

10.3 Using set_range in RANGE mode

Focus on the RANGE mode to demonstrate set_range ()(custom value range) usage and implement "initial interval selection".

#Set the slider value range
slider.set_range(0, 300)
155 42 58 74

10.4 Determine whether the slider is being dragged

The code is as follows:

import display_driver
import lvgl as lv

# Initialize the LVGL core engine
lv.init()

# Screen initialization: set white background
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# Create a normal horizontal slider
slider = lv.slider(scr)
# Set slider size: width 300 pixels, height 50 pixels
slider.set_size(300, 50)
# Set value range: 0~100
slider.set_range(0, 100)
# Display the slider centered
slider.center()

# ===================== Split into two independent Labels =====================
# 1. Value display Label (updated only by the slider callback)
num_label = lv.label(scr)
num_label.set_text("Value: 0")
# Value label position: 70 pixels above the slider, centered
num_label.align(lv.ALIGN.CENTER, 0, -70)

# 2. Drag status Label (updated only by the timer)
status_label = lv.label(scr)
status_label.set_text("Status: Not dragging")
# Status label position: 40 pixels above the slider, centered
status_label.align(lv.ALIGN.CENTER, 0, -40)

# Global variable: stores the current slider value (replaces dynamic attributes, avoids AttributeError)
current_value = slider.get_value()

# ===================== Slider callback: handles only the value Label =====================
# Function: only responds to value changes, updates the value Label + global variable, does not handle any status logic
def slider_event_cb(e):
    global current_value
    # Get the latest value and update the global variable
    current_value = slider.get_value()
    # Update only the value Label
    num_label.set_text(f"Value: {current_value}")
    # Print value update (English)
    print(f"Value updated to: {current_value}")

# Register the value-changed event
slider.add_event_cb(slider_event_cb, lv.EVENT.VALUE_CHANGED, None)

# ===================== Timer: only handles the drag-state Label =====================
# Function: only polls the drag state, updates the text and color of the state Label
def timer_cb(timer):
    # Only check the drag state
    is_dragging = slider.is_dragged()
    # Only update the state Label
    if is_dragging:
        status_label.set_text("Status: Dragging")
        status_label.set_style_text_color(lv.color_hex(0xFF0000), 0)  # Dragging: red
    else:
        status_label.set_text("Status: Not dragging")
        status_label.set_style_text_color(lv.color_hex(0x000000), 0)  # Not dragging: black
    # Print the drag state (in English)
    print(f"Dragging status: {is_dragging}")

# Create a timer: poll every 50ms (adjustable)
timer = lv.timer_create(timer_cb, 50, None)

# Load the screen
lv.screen_load(scr)

In the code above, the interactive slider function is implemented:

  1. First, initialize the LVGL engine and the screen with a white background, create a horizontal slider, set its size and value range, and then display it centered.
  2. Then split two independent labels (the value label and the drag status label), and store the value of the slider via a global variable to avoid the error caused by MicroPython LVGL not supporting dynamic object properties;
  3. The callback function for slider value change is only responsible for updating the text of the value label, synchronizing the global variables, and printing the value update information;
  4. Meanwhile, create an LVGL timer to polling the drag status of the slider every 50ms, only update the text of the status label (display "Dragging" when dragging, "Not dragging" when not dragging) and the font color (red when dragging, black when not dragging), and print the drag status;
  5. The comments throughout the code are in Chinese to facilitate logic understanding, while the printed content is in English, which not only ensures the clear separation of functional responsibilities but also adapts to the compatibility of the operating environment.
31 24
47

11. Line Segments

import display_driver
import lvgl as lv

# Initialize the LVGL core engine
lv.init()

# Screen initialization: set white background
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

#Create a line
line = lv.line(scr)
#Define the vertex coordinates (x, y) of the line
points = [
    lv.point_precise_t({'x': 50, 'y': 50}),
    lv.point_precise_t({'x': 150, 'y': 100}),
    lv.point_precise_t({'x': 250, 'y': 50}),
    lv.point_precise_t({'x': 300, 'y': 150})
]
# Set the vertices of the line
line.set_points(points, len(points))

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

We can use the set_y_invert method to set whether the Y-axis is inverted (to control the drawing direction of the line chart):

line.set_y_invert(True)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

12. Charts and Graphs

Inner Enum Class:

Class nameDescription
chart.TYPEChart type enumeration, used to specify how the chart is displayed:
- NONE: no chart
- LINE: line chart
- BAR: bar chart
- SCATTER: scatter chart
chart.UPDATE_MODEData update mode enumeration, controls how data is displayed when new data is added:
- SHIFT: data shifts left (new data is added on the right, old data shifts left)
- CIRCULAR: circular overwrite (new data overwrites the oldest data)
chart.AXISAxis enumeration, specifies the axis the data is bound to:
- PRIMARY_Y: primary Y axis (default)
- SECONDARY_Y: secondary Y axis
- PRIMARY_X: primary X axis
- SECONDARY_X: secondary X axis
- LAST: last axis

Core Methodology:

Method nameMeaningInput parameters (actually usable format)Return valueNotes
__init__(parent)Chart constructor, creates a chart instanceparent: lv.obj type
(e.g. the screen object scr)
lv.chart objectNone
set_type(type)Sets the chart display typetype: int enum value
(1=LINE line chart,
2=BAR bar chart,
3=SCATTER scatter chart,
0=NONE)
Nonelv.chart.TYPE.LINE actually corresponds to the int value 1; just pass an int directly
set_point_count(count)Sets the maximum number of data points the chart displayscount: int type (e.g. 10/20)NoneNone
set_update_mode(mode)Sets the update logic when new data is addedmode: int enum value
(0=SHIFT shift left,
1=CIRCULAR circular overwrite)
Nonelv.chart.UPDATE_MODE.SHIFT actually corresponds to the int value 0
set_div_line_count(hdiv, vdiv)Sets the number of chart grid lineshdiv: int type (number of horizontal grid lines, e.g. 3);
vdiv: int type (number of vertical grid lines, e.g. 3)
NoneBoth parameters must be passed together; neither can be omitted
set_range(axis, min, max)Sets the value range of the specified axisaxis: int enum value (
0=PRIMARY_Y primary Y axis,
1=SECONDARY_Y secondary Y axis,
2=PRIMARY_X primary X axis,
3=SECONDARY_X secondary X axis);
min: int type (axis minimum value, e.g. 0);
max: int type (axis maximum value, e.g. 100)
NoneAll three parameters must be passed together; lv.chart.AXIS.PRIMARY_Y corresponds to the int value 0
get_type()Gets the current chart typeNoneint enum value (
1=LINE line chart,
2=BAR bar chart, etc.)
Corresponds one-to-one with the int value passed to set_type
get_point_count()Gets the currently set number of data pointsNoneint type (e.g. 10)Same as the value set by set_point_count
get_x_start_point(ser)Gets the X-axis start point index of the specified data seriesser: lv_chart_series_t struct object (created by add_series)int type (e.g. 0)Depends on the series object created by add_series
get_point_pos_by_id(ser, id, p_out)Gets the coordinates of the point in the specified data series by IDser: lv_chart_series_t struct object; id: int type (data point ID, e.g. 0); p_out: lv_point_t struct object (stores the coordinate result)NoneThe coordinate result is stored in the p_out object; no return value
refresh()Forces a chart refresh to update the data / style displayNoneNoneCall after updating data to refresh the interface immediately
add_series(color, axis)Adds a data series (line / bar) to the chartcolor: lv_color_t struct object (e.g. lv.color_hex(0xFF0000));
axis: int enum value (0=PRIMARY_Y primary Y axis)
lv_chart_series_t struct objectThe color does not need to be converted to int; pass the object generated by lv.color_hex directly
remove_series(series)Removes the specified data series from the chartseries: lv_chart_series_t struct objectNoneDepends on the series object created by add_series
hide_series(series, hide)Hides / shows the specified data seriesseries: lv_chart_series_t struct object;
hide: bool type (True = hide, False = show)
NoneDepends on the series object created by add_series
set_series_color(series, color)Sets the display color of the specified data seriesseries: lv_chart_series_t struct object;
color: lv_color_t struct object
NoneDepends on the series object created by add_series
set_x_start_point(ser, id)Sets the X-axis start point index of the specified data seriesser: lv_chart_series_t struct object;
id: int type (start point index, e.g. 0)
NoneDepends on the series object created by add_series
get_series_next(ser)Gets the next series after the specified data series (used for traversal)ser: lv_chart_series_t struct objectlv_chart_series_t struct object (returns None if there is no next one)Depends on the series object created by add_series
add_cursor(color, dir)Adds a cursor to the chart (marks a data point)color: lv_color_t struct object; dir: int enum value (8=DIR.BOTTOM downward)lv_chart_cursor_t struct objectNone
set_cursor_pos(cursor, pos)Sets the cursor position in the chartcursor: lv_chart_cursor_t struct object (created by add_cursor);
pos: lv_point_t struct object (contains x/y coordinates)
NoneDepends on the cursor object created by add_cursor
set_cursor_point(cursor, ser, point_id)Positions the cursor at the specified data point of the specified seriescursor: lv_chart_cursor_t struct object;
ser: lv_chart_series_t struct object;
point_id: int type (data point ID, e.g. 0)
NoneDepends on objects created by add_cursor and add_series
get_cursor_point(cursor)Gets the coordinate point where the cursor is currently positionedcursor: lv_chart_cursor_t struct objectlv_point_t struct object (contains x/y coordinates)Depends on the cursor object created by add_cursor
set_all_value(series, value)Sets all data points of the specified series to the same valueseries: lv_chart_series_t struct object;
value: int type (e.g. 0)
NoneDepends on the series object created by add_series
set_next_value(ser, value)Adds the next Y-axis data point to the specified seriesser: lv_chart_series_t struct object;
value: int type (e.g. 50)
NoneAutomatically processes data according to the mode set by set_update_mode
set_next_value2(ser, x_value, y_value)Adds the next X/Y-axis data point to the specified seriesser: lv_chart_series_t struct object;
x_value: int type (e.g. 1);
y_value: int (e.g., 60)
NoneSupports a custom X-axis value, unlike set_next_value
set_value_by_id(ser, id, value)Set the Y-axis value of the data point with the specified ID in the specified seriesser: lv_chart_series_t struct object;
id: int (data point ID, e.g., 0);
value: int (e.g., 70)
NoneDepends on the series object created by add_series
set_value_by_id2(ser, id, x_value, y_value)Set the X/Y-axis values of the data point with the specified ID in the specified seriesser: lv_chart_series_t struct object;
id: int (data point ID, e.g., 0);
x_value: int (e.g., 2);
y_value: int (e.g., 80)
NoneDepends on the series object created by add_series
set_ext_y_array(ser, array)Bind an external Y-axis data array to the specified seriesser: lv_chart_series_t struct object;
array: list[int] (e.g., [0,10,20,30,40])
NoneDepends on the series object created by add_series
set_ext_x_array(ser, array)Bind an external X-axis data array to the specified seriesser: lv_chart_series_t struct object;
array: list[int] (e.g., [0,10,20,30,40])
NoneDepends on the series object created by add_series
get_y_array(ser)Get the Y-axis data array of the specified seriesser: lv_chart_series_t struct objectC Array (int32 []) (equivalent to Python list[int])Depends on the series object created by add_series
get_x_array(ser)Get the X-axis data array of the specified seriesser: lv_chart_series_t struct objectC Array (int32 []) (equivalent to Python list[int])Depends on the series object created by add_series
get_pressed_point()Get the ID of the data point hit when the user clicks the chartNoneint (2147483647 = no hit; other values are the data point ID)2147483647 is equivalent to -1 (no hit)
get_first_point_center_offset()Get the center offset of the first data point of the chartNoneint type (e.g. 10)The offset is in pixels, used for precise data point positioning

12.1 Line Chart

In the following code, the following operations are performed:

import display_driver
import lvgl as lv
import random
import time

# Initialize the LVGL core engine
lv.init()

# Screen initialization: white background
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# ===================== Create and configure the chart =====================
chart = lv.chart(scr)
chart.set_size(300, 200)  # Chart size
chart.center()            # Center on screen

# Core configuration (strictly matches the APIs that passed testing)
chart.set_type(lv.chart.TYPE.LINE)          # Line chart type
chart.set_point_count(10)                   # Number of data points (shows at most 10)
chart.set_update_mode(lv.chart.UPDATE_MODE.SHIFT)  # Data shifts left on update
chart.set_div_line_count(3, 3)              # Grid lines: 3 horizontal + 3 vertical (2 parameters, passed testing)
chart.set_range(lv.chart.AXIS.PRIMARY_Y, 0, 100)  # Y-axis range: 0~100 (3 parameters, passed testing)

# ===================== Add data series =====================
# Pass the color object + AXIS constant directly (passed testing, no int conversion needed)
# Red line
ser1 = chart.add_series(lv.color_hex(0xFF0000), lv.chart.AXIS.PRIMARY_Y)  
# Blue line
ser2 = chart.add_series(lv.color_hex(0x0000FF), lv.chart.AXIS.PRIMARY_Y)  

# ===================== Initialize data =====================
chart.set_all_value(ser1, 0)  # Initialize the red line to 0 (2 parameters, passed testing)
chart.set_all_value(ser2, 0)  # Initialize the blue line to 0

# ===================== Timer: update data in real time =====================
def update_chart(timer):
    """Timer callback: generate random data and update the chart"""
    val1 = random.randint(20, 80)  # Random value for the red line
    val2 = random.randint(10, 90)  # Random value for the blue line
    
    chart.set_next_value(ser1, val1)  # Update the red line data
    chart.set_next_value(ser2, val2)  # Update the blue line data
    
    print(f"Updated: ser1={val1}, ser2={val2}")  # English log output

# Create a timer: 500ms period, repeatedly runs the update function (regular function callback, passed testing)
lv.timer_create(update_chart, 500, None)

# ===================== Load the screen =====================
lv.screen_load(scr)
3 0 500ms ser1 57 ser2 28
v9.0 12.1 3

12.2 Bar Chart

The code below displays a bar chart with a white background, which consists of 6 groups of red and blue bars, with the Y-axis ranging from 0 to 100, along with 3 horizontal grid lines and 2 vertical grid lines.

import display_driver
import lvgl as lv
import random
import time

# Initialize the LVGL core engine
lv.init()

# Screen initialization: white background
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

# Create a bar chart
chart = lv.chart(scr)
chart.set_size(300, 220)  # Set the chart size: width 300, height 220
chart.center()            # Center the chart on screen

# Configure the chart as a bar chart type (pass lv.chart.TYPE.BAR directly, passed testing)
chart.set_type(lv.chart.TYPE.BAR)
# Set the number of data points (number of bars): 6
chart.set_point_count(6)
# Set the grid lines: 3 horizontal lines, 2 vertical lines (2 parameters, passed testing)
chart.set_div_line_count(3, 2)
# Y-axis range 0~100
chart.set_range(lv.chart.AXIS.PRIMARY_Y, 0, 100)  

# First group: red bars, using the primary Y axis (pass the color object + AXIS constant directly, passed testing)
ser1 = chart.add_series(lv.color_hex(0xFF5733), lv.chart.AXIS.PRIMARY_Y)
# Second group: blue bars, using the primary Y axis
ser2 = chart.add_series(lv.color_hex(0x3377FF), lv.chart.AXIS.PRIMARY_Y)

# Set the first group of data
data1 = [30, 45, 28, 67, 50, 75]
for idx, value in enumerate(data1):
    # Set the Y-axis values one by one by ID
    chart.set_value_by_id(ser1, idx, value)  
    
# Set the second group of data
data2 = [20, 55, 38, 47, 60, 55]
for idx, value in enumerate(data2):
    chart.set_value_by_id(ser2, idx, value)

# Load the screen
lv.screen_load(scr)
12.2 6 0 100 3 2

12.3 Scatter Plot

It should be noted that, the SCATTER (scatter chart) type of LVGL is not a scatter chart in the traditional sense that only displays independent discrete points; instead, it automatically connects adjacent Data Points of the same series with polylines, presenting the effect of a "polyline with Data Points", which is significantly different from the scatter chart without connections that we conventionally recognize.This feature makes it more suitable for trajectory update scenarios, such as real-time display of device movement trajectories (e. g., sensor positions, mobile terminal positioning), dynamic change trajectories of multi-dimensional indicators (e. g., XY-axis trend tracking of industrial monitoring data), etc. It can intuitively present the continuous change path of the same type of data on the XY plane, rather than simply displaying the distribution of discrete points.

import display_driver
import lvgl as lv
import time
import random

# ===================== 1. Initialize the LVGL environment =====================
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  # Black background to make the scatter points stand out

# ===================== 2. Core configuration for creating a planar scatter chart =====================
chart = lv.chart(scr)
chart.set_size(400, 300)  # Larger size, suited to XY dual-axis distribution
chart.center()

# Key configuration: dual-axis scatter chart
chart.set_type(lv.chart.TYPE.SCATTER)          # Pure scatter chart type
chart.set_point_count(20)                      # Shows at most 20 scatter points (shift update)
chart.set_update_mode(lv.chart.UPDATE_MODE.CIRCULAR)  # New points added on the right, old points shift left
chart.set_div_line_count(5, 5)                 # 5 horizontal and 5 vertical grid lines, evenly dividing the XY axes

# Set the XY dual-axis ranges (planar coordinate system: X 0-100, Y 0-100)
chart.set_range(lv.chart.AXIS.PRIMARY_X, 0, 100)  # X-axis range
chart.set_range(lv.chart.AXIS.PRIMARY_Y, 0, 100)  # Y-axis range

# ===================== 3. Add three-color scatter series (different XY ranges) =====================
# Red scatter points: upper-left region (X 10-30, Y 70-90)
ser_red = chart.add_series(lv.color_hex(0xFF0000), lv.chart.AXIS.PRIMARY_Y)
# Blue scatter points: middle region (X 40-60, Y 40-60)
ser_blue = chart.add_series(lv.color_hex(0x0000FF), lv.chart.AXIS.PRIMARY_Y)
# Yellow scatter points: lower-right region (X 70-90, Y 10-30)
ser_yellow = chart.add_series(lv.color_hex(0xFFFF00), lv.chart.AXIS.PRIMARY_Y)

# ===================== 4. Initialize scatter data (initially 0) =====================
chart.set_all_value(ser_red, 0)
chart.set_all_value(ser_blue, 0)
chart.set_all_value(ser_yellow, 0)

# ===================== 5. Timer: update the planar scatter in real time (random XY) =====================
def update_scatter(timer):
    """Generate random XY values in different ranges and update the planar scatter points"""
    # Red: upper-left region (X 10-30, Y 70-90)
    x_red = random.randint(10, 30)
    y_red = random.randint(70, 90)
    chart.set_next_value2(ser_red, x_red, y_red)  # Dual-axis update: X+Y

    # Blue: middle region (X 40-60, Y 40-60)
    x_blue = random.randint(40, 60)
    y_blue = random.randint(40, 60)
    chart.set_next_value2(ser_blue, x_blue, y_blue)

    # Yellow: lower-right region (X 70-90, Y 10-30)
    x_yellow = random.randint(70, 90)
    y_yellow = random.randint(10, 30)
    chart.set_next_value2(ser_yellow, x_yellow, y_yellow)

    # Print real-time coordinates (optional, to view the data)
    print(f"Red({x_red},{y_red}) | Blue({x_blue},{y_blue}) | Yellow({x_yellow},{y_yellow})")

# Create a timer: update the scatter points every 600ms
lv.timer_create(update_scatter, 600, None)

# ===================== 6. Load the screen and keep running =====================
lv.screen_load(scr)
5

In the code above, the dynamic scatter plot effect with XY dual axes is implemented based on the LVGL graphics library: First, initialize the chart with a black background, configure the value range of 0-100 for the XY axes and the 5×5 uniform grid lines, create three data series in red, blue and yellow corresponding to different XY coordinate intervals of upper left, middle and lower right respectively, and generate random XY coordinates in the corresponding intervals every 600ms via a timer. With the help of set_next_value2 method, the dual-axis Data Points of each series are updated to realize the dynamic refresh of data.

13. Calendar

API namePurpose
initConstruct a calendar widget, bound to the parent container
set_today_dateSet today's date of the calendar
set_highlighted_datesSet the dates to be highlighted in the calendar
set_day_namesSet the weekday names at the top of the calendar
get_btnmatrixGet the internal button matrix object of the calendar
get_today_dateGet today's date set in the calendar
get_showed_dateGet the year and month currently displayed by the calendar
get_highlighted_datesGet the list of highlighted dates of the calendar
get_highlighted_dates_numGet the total number of highlighted dates
get_pressed_dateGet the date currently selected by clicking
header_dropdown_set_year_listSet the year list of the drop-down in the calendar header

The list of actually tested and available APIs is as follows:

API nameMeaningInput parametersReturn value
lv.calendar.__init__Construct a calendar widget, bound to the specified parent containerparent: lv.obj (e.g., the screen object scr)lv.calendar (calendar widget object)
set_today_dateSet today's date of the calendarThree int parameters:
year, month, day
No return value
set_showed_dateSet the year and month currently displayed by the calendarTwo int parameters:
year, month
No return value
set_highlighted_datesSet the dates to be highlighted in the calendar1. Highlighted date list: list of lv_calendar_date_t objects (each object must have its year/month/day attributes configured);
2. date_num: int, the number of highlighted dates
No return value
get_btnmatrixGet the internal button matrix object of the calendarNo input parameterslv.buttonmatrix
(button matrix object)
get_today_dateGet the today's date already set in the calendarNo input parameterslv_calendar_date_t object
(with year/month/day attributes)
get_showed_dateGet the year and month currently displayed by the calendarNo input parameterslv_calendar_date_t object
(with year/month attributes)
get_highlighted_datesGet the highlighted dates of the calendar (environment limitation: only the first highlighted date is returned)No input parameterslv_calendar_date_t object
(with year/month/day attributes)
get_highlighted_dates_numGet the total number of highlighted dates in the calendarNo input parametersint (number of highlighted dates)
header_dropdown_set_year_listSet the year list of the drop-down in the calendar headerA single str parameter: year string (separate different years with the newline character \n, e.g., "2020\n2021\n2022")No return value

13.1 Basic Calendar Initialization

import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

#Create a calendar object
calendar = lv.calendar(scr)
#Set the size
calendar.set_size(250, 250)
#Center it
calendar.center()
# Set today's date (March 16, 2026)
calendar.set_today_date(2026, 03, 16)
 # Set the displayed year and month directly
calendar.set_showed_date(2026, 03)

# Load the screen
lv.screen_load(scr)
16 13.2

13.2 Highlighted Date Setting and Query

The following code simulates the actual scenario of "marking holidays / important schedules", which is the most commonly used business function of the calendar:

import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

calendar = lv.calendar(scr)
calendar.set_size(300, 300)
calendar.center()
calendar.set_today_date(2026, 3, 16)
# Set the displayed year and month directly
calendar.set_showed_date(2026, 03)

# ========== Core API calls ==========
# 1. Construct the highlighted date objects (must use lv_calendar_date_t, required by the environment)
# Highlight March 8 (Women's Day) and March 20 (important meeting)
highlight_date1 = lv.calendar_date_t()
highlight_date1.year, highlight_date1.month, highlight_date1.day = 2026, 3, 8

highlight_date2 = lv.calendar_date_t()
highlight_date2.year, highlight_date2.month, highlight_date2.day = 2026, 3, 20

# 2. set_highlighted_dates: set the highlighted dates (arguments: list of date objects + count int)
calendar.set_highlighted_dates([highlight_date1, highlight_date2], 2)

# 3. get_highlighted_dates_num: get the total number of highlighted dates (returns int)
highlight_count = calendar.get_highlighted_dates_num()
print(f"Total Highlighted Dates: {highlight_count}")

# 4. get_highlighted_dates: get the first highlighted date (environment limitation: only returns the first one)
first_highlight = calendar.get_highlighted_dates()
print(f"First Highlighted Date: {first_highlight.year}-{first_highlight.month}-{first_highlight.day}")

# Load the screen
lv.screen_load(scr)
2024 10 8 16 20 13.2

14. Text Box

API namePurposeInput parametersReturn value
__init__Construct a Textarea widget, bound to the specified parent containerparent: lv.obj type
(parent container object)
lv.textarea
add_charAdd a single character (the argument is a character code / delay value, actually used for character input)delay_ms: int
(character code / delay in milliseconds)
None
add_textAppend text content to the text boxtext: str (text to add)None
delete_charDelete the character to the left of the cursorNoneNone
set_textSet the complete content of the text box (overwrites the existing content)text: str (target text)None
get_textGet all the current content of the text boxNonestr
set_placeholder_textSet the placeholder hint text displayed when the text box is emptytext: str (placeholder text)None
get_placeholder_textGet the placeholder hint text of the text boxNonestr
set_cursor_posSet the cursor position (by character index, starting from 0)index: int (cursor index position)None
get_cursor_posGet the index position where the cursor is currently locatedNoneint
set_cursor_click_posSet whether the cursor is automatically positioned when the text box is clickedantialias: bool
(True = on, False = off)
None
get_cursor_click_posGet the on/off state of "click to position cursor"Nonebool
cursor_rightMove the cursor one character position to the rightNoneNone
cursor_leftMove the cursor one character position to the leftNoneNone
cursor_downMove the cursor down one line (in multi-line mode)NoneNone
cursor_upMove the cursor up one line (in multi-line mode)NoneNone
set_password_modeTurn password input mode on / off (input content is masked)antialias: bool
(True = on, False = off)
None
set_password_bulletSet the mask character in password mode (e.g., *, ●)text: str
(mask character, a single character recommended)
None
get_password_bulletGet the mask character of the current password modeNonestr
set_password_show_timeSet how long a password character stays visible after input (in milliseconds; becomes masked after the timeout)delay_ms: int
(display duration, in ms)
None
get_password_show_timeGet the visible duration of password charactersNoneint
set_one_lineSet whether the text box displays only a single line (False = multi-line allowed)antialias: bool
(True = single line, False = multi-line)
None
get_one_lineGet the single-line / multi-line display state of the text boxNonebool
set_accepted_charsSet the set of characters the text box allows to be entered (characters outside it cannot be entered)text: str
(allowed characters, e.g., "0-9a-z")
None
get_accepted_charsGet the set of characters currently allowed for inputNonestr
set_max_lengthSet the maximum character length the text box allows to be entereddelay_ms: int (maximum length value)None
set_insert_replaceSet the replacement text in insert mode (replaces the selected content when typing)text: str (replacement text)None
set_text_selectionTurn the text selection function on / off (allows part of the text to be selected)antialias: bool
(True = on, False = off)
None
get_text_selectionGet the on/off state of the text selection functionNonebool
text_is_selectedCheck whether any text is currently selectedNonebool
clear_selectionClear the currently selected text (cancel the selection state)NoneNone
get_current_charGet the ASCII/Unicode code value of the character at the cursor positionNoneint
get_labelGet the Label object (underlying widget) used internally by the text box to render textNonelv.label

14.1 Plain Text Box

import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

# Create a regular text box (multi-line input)
textarea1 = lv.textarea(scr)
textarea1.set_size(lv.pct(90), 100)
textarea1.set_pos(lv.pct(5), lv.pct(5))
textarea1.set_placeholder_text("Multi-line input...")
textarea1.set_max_length(100)  # Maximum 100 characters

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

14.2 Password Box

import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

# Create a password box
password_area = lv.textarea(scr)
password_area.set_size(lv.pct(90), 50)
password_area.set_pos(lv.pct(5), lv.pct(35))
password_area.set_placeholder_text("Please enter the password.")
password_area.set_password_mode(True)
password_area.set_password_bullet("•")  # Password shown as dots
password_area.set_password_show_time(1000)  # Typed characters are shown for 1 second and then change to dots
password_area.set_max_length(20)  # Password maximum 20 characters

# Load the screen
lv.screen_load(scr)
v9.0 14.2

14.3 Text Box Allowing Numeric Input Only

import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

# Create a text box with a character limit (digits only)
number_area = lv.textarea(scr)
number_area.set_size(lv.pct(90), 50)
number_area.set_pos(lv.pct(5), lv.pct(55))
number_area.set_placeholder_text("Please enter a number")
number_area.set_one_line(True)  # Single-line mode
number_area.set_accepted_chars("0123456789")  # Only digit input allowed
number_area.set_max_length(10)  # Maximum 10 digits

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

15. Keyboard

API namePurposeInput parametersReturn valueNotes
__init__Construct a keyboard widget, bound to the specified parent containerparent: lv.obj (e.g., the screen object scr)lv.keyboardBasic creation
set_textareaBind the keyboard to a Textarea to link input (core)obj: lv.textarea (text box to bind)NoneInput content is automatically synchronized to the text box
get_textareaGet the currently bound Textarea objectNonelv.textareaVerify whether the binding is in effect
set_modeSet the keyboard input modemode: int (enum value) 0=TEXT_LOWER (lowercase) 1=TEXT_UPPER (uppercase) 3=NUMBER (numbers)NoneSwitch the input mode as needed
get_modeGet the current keyboard modeNoneintReturn the mode enum value
set_popoversTurn the special character pop-up layer on / off (e.g., punctuation, symbols)antialias: bool (True = on)NoneEnhance special character input
set_mapCustomize the keyboard key layout of the specified mode1. mode: int (mode) 2. map: list [str] (button text) 3. ctrl_map: NoneNoneSimplified: pass None for ctrl_map
get_selected_buttonGet the ID of the currently selected button (returns 65535 if none selected)NoneintAids interaction logic
get_button_textGet the button display text by button IDbtn_id: int (button ID, starting from 0)strVerify that the custom layout takes effect

15.1 General Single Text Box Input Keyboard

import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)  

#Create a keyboard
keyboard = lv.keyboard(scr)
#Set the size
keyboard.set_size(400, 200)
#Align to bottom center
keyboard.align(lv.ALIGN.BOTTOM_MID, 0, 0)  
# Create the input target (using textarea as an example)
textarea = lv.textarea(scr)
textarea.set_size(380, 100)
textarea.align(lv.ALIGN.TOP_MID, 0, 20)
textarea.set_placeholder_text("textarea...")  # Placeholder text
# Bind the keyboard to the input target; once bound, keyboard input goes directly into the textarea
keyboard.set_textarea(textarea) 

# Load the screen
lv.screen_load(scr)
1 123 15.1
1 15.1

15.2 Plain Text Numeric Input Box with Keyboard Show/Hide Control

In the following code, we implement a minimalist example of numeric input interaction, retaining only the core functions of "plaintext numeric input + virtual numeric keypad":

import display_driver
import lvgl as lv

lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)
scr_h = scr.get_height()  # Get the screen height

# Create a plain-text numeric input box (core)
textarea = lv.textarea(scr)
textarea.set_size(380, 50)  # Fixed size
textarea.set_pos(10, 20)     # Fixed position
textarea.set_placeholder_text("Please enter the number.")
textarea.set_accepted_chars("0123456789")  # Digits only
textarea.set_one_line(True)                # Single line
textarea.set_max_length(6)                 # 6-digit limit

# Create a numeric keyboard (initially moved off screen)
kb = lv.keyboard(scr)
kb.set_size(400, 200)       # Fixed size
kb.set_pos(0, scr_h + 100)  # Initially hidden (off screen)
kb.set_mode(lv.keyboard.MODE.NUMBER)  # Digits-only mode

# Keyboard show/hide logic (minimal)
def show_kb(e):
    """Tap the input box: show the keyboard"""
    kb.set_textarea(textarea)
    # Move to the bottom of the screen
    kb.set_pos(0, scr_h - 350)  

def hide_kb(e):
    """Confirm/Enter: hide the keyboard"""
    if e.get_code() == lv.EVENT.READY:
        # Move back off screen
        kb.set_pos(0, scr_h + 100)  

# 5. Bind events
textarea.add_event_cb(show_kb, lv.EVENT.CLICKED, None)
kb.add_event_cb(hide_kb, lv.EVENT.READY, None)

# 6. Run
lv.screen_load(scr)
15.2 0 9 6

Tap the text box to bring up the keyboard, then tap the [checkmark] to dismiss the keyboard:

158698 0 9 15.2

Scroll down to view the keyboard:

1 9 0 15.2

15.3 Dual Text Boxes (Standard + Numeric) Sharing a Virtual Keyboard

The following code implements the function of sharing one virtual keyboard for both a regular text box and a numeric text box, with automatic switching of keyboard input modes:

The code is as follows:

import display_driver
import lvgl as lv

# 1. Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)
scr_h = scr.get_height()  # Get the screen height

# 2. Create two text boxes
# 2.1 Plain text box (no character limit)
text_normal = lv.textarea(scr)
text_normal.set_size(380, 50)
text_normal.set_pos(10, 20)
text_normal.set_placeholder_text("Normal text...")
text_normal.set_one_line(True)

# 2.2 Numeric text box (digits only, 6-character limit)
text_number = lv.textarea(scr)
text_number.set_size(380, 50)
text_number.set_pos(10, 90)
text_number.set_placeholder_text("Number only...")
text_number.set_accepted_chars("0123456789")
text_number.set_one_line(True)
text_number.set_max_length(6)

# 3. Create a shared virtual keyboard (initially hidden off-screen)
kb = lv.keyboard(scr)
kb.set_size(400, 200)
kb.set_pos(0, scr_h + 100)  # Initially off-screen

# 4. Keyboard show/hide + binding logic (core: switch the bound text box)
def show_kb_normal(e):
    """Tap the plain text box: bind + show the keyboard (default text mode)"""
    kb.set_textarea(text_normal)
    kb.set_mode(lv.keyboard.MODE.TEXT_LOWER)  # Plain text mode
    kb.set_pos(0, scr_h - 350)  # Move to the bottom of the screen

def show_kb_number(e):
    """Tap the numeric text box: bind + show the keyboard (numeric mode)"""
    kb.set_textarea(text_number)
    kb.set_mode(lv.keyboard.MODE.NUMBER)  # Digits-only mode
    kb.set_pos(0, scr_h - 300)  # Move to the bottom of the screen

def hide_kb(e):
    """Confirm/Enter: hide the keyboard"""
    if e.get_code() == lv.EVENT.READY:
        kb.set_pos(0, scr_h + 100)  # Move back off-screen

# 5. Bind events
text_normal.add_event_cb(show_kb_normal, lv.EVENT.CLICKED, None)
text_number.add_event_cb(show_kb_number, lv.EVENT.CLICKED, None)
kb.add_event_cb(hide_kb, lv.EVENT.READY, None)

# 6. Run
lv.screen_load(scr)
0-9 26 15.3

Tap the general text box, and the full keyboard will appear; tap the check mark, and the keyboard will disappear.

0-9

Tap the number input box, and the number input box appears; tap the checkmark, and the keyboard disappears.

16. Drop-down List

API nameMeaningInput parametersReturn value
set_textSet the text displayed by the dropdown liststr (text to display)None
set_optionsSet the dropdown list options (dynamic string)str (options separated by newline character \n)None
set_options_staticSet the dropdown list options (static string)str (options separated by newline character \n)None
add_optionAdd a single option at the specified positionstr (option text), int (insertion position index)None
clear_optionsClear all options of the dropdown listNo parametersNone
set_selectedSet the default selected option of the dropdown listint (index of the selected item, starting from 0)None
set_dirSet the expansion direction of the dropdown listint (direction enum value, e.g., 0 = down, 1 = up)None
set_symbolSet the arrow symbol on the right side of the dropdown liststr (symbol identifier, e.g., "LV_SYMBOL_DOWN")None
set_selected_highlightSet whether the selected item is highlightedbool (True = highlighted, False = not highlighted)None
get_listGet the underlying list container object of the dropdown listNo parametersobj (list container object)
get_textGet the text currently displayed by the dropdown listNo parametersstr (display text)
get_optionsGet all options of the dropdown list (newline-separated)No parametersstr (text of all options)
get_selectedGet the index of the currently selected item (core method)No parametersint (index of the selected item)
get_option_countGet the total number of options in the dropdown listNo parametersint (number of options)
get_selected_strWrite the selected item's text to the specified bufferstr (buffer), int (buffer size)None
get_option_indexGet the corresponding index from the option textstr (option text to look up)int (corresponding index, returns -1 if no match)
get_symbolGet the text of the dropdown list's current arrow symbolNo parametersstr (symbol text)
get_selected_highlightGet whether the selected item is highlightedNo parametersbool (highlight state)
get_dirGet the current expansion direction of the dropdown listNo parametersint (direction enum value)
openManually expand the dropdown listNo parametersNone
closeManually collapse the dropdown listNo parametersNone
is_openCheck whether the dropdown list is expandedNo parametersbool (expanded state)
bind_valueBind an observer for value changes (advanced feature)NoneType (pass None for simplified testing)None

16.1 Simple Dropdown List

The following code implements a minimalist drop-down list interaction function:

  1. First, initialize the LVGL environment and set the screen background to solid black, then create a drop-down list control and center it on the screen, and configure 4 selectable options for this drop-down list, namely "case 1" to "case 4"(separated by line breaks);
  2. Then, an interaction callback function is defined. When the selected item of the drop-down list changes, this function will obtain the index value of the currently selected item and print it out in the format of "choose ID: index value";
  3. Finally, bind this callback function to the "value change" event of the drop-down list, and refresh the screen to activate the entire drop-down list interface, so as to finally implement the core interaction logic of "select a drop-down list option → print the index of the selected item".
import display_driver
import lvgl as lv

# Initialize the environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the dropdown widget
dropdown = lv.dropdown(scr)
#Center it
dropdown.center()
#A string separated by newline characters represents multiple options
dropdown.set_options("case 1\ncase 2\ncase 3\ncase 4")

#Interaction callback function
def dropdown_event_cd(e):
    #Get the index of the currently selected option
    selected_option = dropdown.get_selected()
    #Get the index of the currently selected option
    print(f"choose ID: {selected_option}")

#Register the interaction callback function. For more states see the "class EVENT" section of api.py
dropdown.add_event_cb(dropdown_event_cd, lv.EVENT.VALUE_CHANGED, None)

lv.screen_load(scr)
4 1 2 0 3

16.2 Get the text of the selected item

In the following example, the basic interaction of the drop-down list is implemented, which not only obtains the index of the selected item, but also parses the corresponding text content:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the dropdown widget and center it
dropdown = lv.dropdown(scr)
dropdown.center()
# Set the dropdown options (business scenario: select a device model)
options = "Model A\nModel B\nModel C\nModel D"
dropdown.set_options(options)

# Interaction callback: get the index and text of the selected item
def dropdown_event_cb(e):
    # Get the index of the currently selected item
    selected_idx = dropdown.get_selected()
    # Get all options and split them by newline
    all_options = dropdown.get_options().split("\n")
    # Safely get the selected text (avoid index out of range)
    selected_text = all_options[selected_idx] if 0 <= selected_idx < len(all_options) else "Unknown"
    # Print the selected result (English output)
    print(f"Selected index: {selected_idx} | Selected text: {selected_text}")

# Bind the value-changed event: trigger the callback when the selected item changes
dropdown.add_event_cb(dropdown_event_cb, lv.EVENT.VALUE_CHANGED, None)

# Load the screen to make the interface take effect
lv.screen_load(scr)
v9.0 1 2 3 16.2

16.3 Dynamically Add and Remove Options

The following code demonstrates dynamically adding/clearing dropdown list options at runtime to adapt to the scenario of "updating selectable configurations based on device status"(e. g., updating communication methods based on device connection status):

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the dropdown widget, set a fixed size and position
dropdown = lv.dropdown(scr)
dropdown.set_pos(20, 20)
dropdown.set_size(200, 50)
# Initialize with empty options
dropdown.set_options("")

# Function: dynamically add options (simulate loading communication method configuration)
def add_options():
    # Add options at the specified index positions (WiFi/Bluetooth/Ethernet)
    dropdown.add_option("WiFi", 0)
    dropdown.add_option("Bluetooth", 1)
    dropdown.add_option("Ethernet", 2)
    # Print the current total number of options
    print(f"Current option count: {dropdown.get_option_count()}")

# Function: clear all options (simulate resetting the configuration)
def clear_all_options():
    dropdown.clear_options()
    # Print the total number of options after clearing
    print(f"Option count after clear: {dropdown.get_option_count()}")

# Call the function at initialization to add options
add_options()

# Interaction callback: clear all options when the last item (Ethernet) is selected
def dropdown_event_cb(e):
    if dropdown.get_selected() == 2:
        clear_all_options()

# Bind the value-changed event
dropdown.add_event_cb(dropdown_event_cb, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)
4 0

16.4 Button Control for Dropdown List Expansion/Collapse

In the following example, the expand/collapse state of the drop-down list is manually controlled via a button control:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# 1. Create the dropdown widget, set its position and size
dropdown = lv.dropdown(scr)
dropdown.set_pos(lv.pct(10), lv.pct(20))
dropdown.set_size(200, 50)
# Set the dropdown options
dropdown.set_options("Option 1\nOption 2\nOption 3")

# 2. Create a control button: used to expand/collapse the dropdown
btn_open = lv.button(scr)
btn_open.set_pos(lv.pct(10), lv.pct(5))
btn_open.set_size(100, 40)
# Add a text label to the button
btn_label = lv.label(btn_open)
btn_label.set_text("Open List")
btn_label.center()

# Button callback: toggle the dropdown's expanded/collapsed state
def btn_event_cb(e):
    if dropdown.is_open():
        # Collapse the dropdown
        dropdown.close()
        btn_label.set_text("Open List")
    else:
        # Expand the dropdown
        dropdown.open()
        btn_label.set_text("Close List")

# Bind the button click event
btn_open.add_event_cb(btn_event_cb, lv.EVENT.CLICKED, None)

# Dropdown callback: print the index of the selected item
def dropdown_event_cb(e):
    print(f"Selected option index: {dropdown.get_selected()}")

# Bind the dropdown value-changed event
dropdown.add_event_cb(dropdown_event_cb, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)
v1.20.0 1053 g349ae32bf 2024 09 11 1 2 3
1

17. Scroll Wheel

API namePurposeInput parametersReturn value
set_optionsSet the roller options (separated by newline characters) and scroll mode (normal / infinite loop)1st parameter: str (roller options, separated by \n);
2nd parameter: int (scroll mode, lv.roller.MODE.NORMAL=0/INFINITE=1)
None
set_selectedSet the roller's selected item by index, and control whether animation is enabled1st parameter: int (selected item index, starting from 0);
2nd parameter: int (animation switch, lv.ANIM.OFF=0/ON=1)
None
set_visible_row_countSet the number of visible rows of the roller to control the visual displayint (number of visible rows, 3-5 rows recommended)None
get_selectedGet the index of the roller's currently selected item (core read method)No parametersint (index of the selected item)
get_selected_strWrite the text of the roller's currently selected item into the specified buffer1st parameter: str (buffer to receive the selected text);
2nd parameter: int (buffer size)
None
get_optionsGet the string of all roller options (separated by \n)No parametersstr (all options, separated by \n)
get_option_countGet the total number of roller optionsNo parametersint (total number of options)
bind_valueBind an observer for value changes (advanced feature, beginners can ignore)NoneType (actually subject_t type, just pass None when testing)None

set_selected (sel_opt: int, anim: int) the second parameter of anim (animation toggle), which controls whether the scroll wheel performs the "smooth scroll to target item" animation when the selected item is set via code, essentially distinguishing between "instant switch" and "smooth scroll switch":

Parameter valueActual MeaningVisual Effect Example
lv.ANIM.OFFAnimation off (value 0)The selected item jumps instantly to the target index (e.g., from index 0 straight to index 5, with no transition); switching is extremely fast
lv.ANIM.ONAnimation on (value 1)The selected item scrolls smoothly from its current position to the target index (e.g., from 0 to 5, with the intermediate options visibly passing by one after another); the transition is more user-friendly

The core differences between the two scrolling modes of the Roller control are shown in the following table:

ComparisonNormal mode (MODE.NORMAL)Infinite loop mode (MODE.INFINITE)
Constant value (SDL environment)lv.roller.MODE.NORMAL = 0lv.roller.MODE.INFINITE = 1
Core BehaviorThe roller has clear "first/last boundaries"; once it reaches a boundary, it cannot scroll further in that directionThe roller has no boundaries; scrolling past the last item wraps back to the first item, and scrolling past the first item wraps back to the last item
Scroll Boundary ExampleAfter the weekday roller reaches Sunday (index 6), scrolling down has no effect; after it reaches Monday (index 0), scrolling up has no effectAfter the month roller reaches December (index 11), scrolling down jumps to January (index 0); after reaching January, scrolling up jumps to December
Visual ExperienceGives clear "reached the bottom/top" feedback, so the user knows the boundary has been reachedNo sense of a boundary; scrolling loops smoothly, suitable for options with no clear first/last (such as months, numbers, years)
Applicable scenariosOptions with a fixed first and last (weekdays, day of the week, days of the week)Options with no fixed first/last, or that need cyclic selection (months, years, hours, minutes)

17.1 Examples of Week Selection (Normal Mode) and Month Selection (Infinite Loop Mode)

In the following code, two side-by-side scroll wheels will be displayed on the screen: the left one is a "weekday scroll wheel" that can only scroll to the start and end, while the right one is a "month scroll wheel" that supports infinite looping scrolling:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

#Create a normal-mode roller widget (weekday selection)
roller_normal = lv.roller(scr)
roller_normal.set_pos(20, 20)
roller_normal.set_size(200, 150)
#Set the options and normal mode
# Define a string containing Monday to Sunday (options separated by newline \n)
# Set it as the roller options, and set the roller to normal mode (MODE.NORMAL)
days = "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday"
roller_normal.set_options(days, roller_normal.MODE.NORMAL)
#Set the number of visible rows: the roller area shows at most 5 options at the same time
roller_normal.set_visible_row_count(5)

#Create an infinite-mode roller (month selection)
roller_infinite = lv.roller(scr)
roller_infinite.set_pos(240, 20)
roller_infinite.set_size(200, 150)
#Set the options and infinite mode
months = "January\nFebruary\nMarch\nApril\nMay\nJune\nJuly\nAugust\nSeptember\nOctober\nNovember\nDecember"
# Set the roller to infinite loop mode (MODE.INFINITE)
# In this mode the roller has no first/last limit; after scrolling to the last option (December), scrolling further jumps back to the first option (January)
roller_infinite.set_options(months, roller_normal.MODE.INFINITE)
#Set the number of visible rows
roller_infinite.set_visible_row_count(5)

# Load the screen
lv.screen_load(scr)
v9.0

17.2 Change the Number of Visible Rows

#Set the number of visible rows: the roller area shows at most 6 options at the same time
roller_normal.set_visible_row_count(6)
v9.0

17.3 Read All Selections and Current Selection

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# ===================== 1. Normal-mode roller (weekday selection) =====================
roller_normal = lv.roller(scr)
roller_normal.set_pos(20, 20)
roller_normal.set_size(200, 150)
# Configure the weekday options + normal mode
days = "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday"
roller_normal.set_options(days, lv.roller.MODE.NORMAL)
roller_normal.set_visible_row_count(5)
# Demonstrate set_selected: initially select index 2 (Wednesday) by default, with animation off
roller_normal.set_selected(2, lv.ANIM.OFF)
print(f"[Week Roller] Default selected index: {roller_normal.get_selected()}")

# ===================== 2. Infinite-loop-mode roller (month selection) =====================
roller_infinite = lv.roller(scr)
roller_infinite.set_pos(240, 20)
roller_infinite.set_size(200, 150)
# Configure the month options + infinite loop mode
months = "January\nFebruary\nMarch\nApril\nMay\nJune\nJuly\nAugust\nSeptember\nOctober\nNovember\nDecember"
roller_infinite.set_options(months, lv.roller.MODE.INFINITE)
roller_infinite.set_visible_row_count(5)

# ===================== 3. Dedicated callback functions (separated, core approach) =====================
# ---------- Callback 1: dedicated to the weekday roller (demonstrates get_options / get_selected_str) ----------
def roller_week_cb(e):
    # Operate directly on the global roller_normal, no need to get the target object
    print("\n=== [Week Roller] Value Changed ===")
    
    # 🔍 Demonstrate get_options: get all options (a newline-separated string)
    all_options = roller_normal.get_options()
    option_count = roller_normal.get_option_count()
    print(f"Total options: {option_count}")
    print(f"All options string: {all_options}")
    
    # 🔍 Demonstrate get_selected_str: get the selected text through a buffer (core API)
    buf = ""  # Define an empty buffer to receive the selected text
    buf_size = 30  # Buffer size (must be larger than the longest selected text)
    roller_normal.get_selected_str(buf, buf_size)  # Core call: write into the buffer
    print(f"Selected text (by get_selected_str): {buf}")
    
    # 🔍 Auxiliary verification: get the text through get_selected + splitting get_options
    selected_idx = roller_normal.get_selected()
    selected_text_split = all_options.split("\n")[selected_idx]
    print(f"Selected index: {selected_idx} | Text (split): {selected_text_split}")

# ---------- Callback 2: dedicated to the month roller (demonstrates infinite mode + the same API) ----------
def roller_month_cb(e):
    # Operate directly on the global roller_infinite
    print("\n=== [Month Roller] Value Changed ===")
    
    # 🔍 Demonstrate get_options: get all options (also works in infinite mode)
    all_options = roller_infinite.get_options()
    option_count = roller_infinite.get_option_count()
    print(f"Total options: {option_count}")
    
    # 🔍 Demonstrate get_selected_str: read the selected text in infinite mode
    buf = ""
    buf_size = 30
    roller_infinite.get_selected_str(buf, buf_size)
    print(f"Selected text: {buf}")
    
    # 🔍 Auxiliary verification: index splitting method
    selected_idx = roller_infinite.get_selected()
    selected_text_split = all_options.split("\n")[selected_idx]
    print(f"Selected index: {selected_idx} | Text: {selected_text_split}")

# ===================== 4. Bind the dedicated callbacks (no user_data, no errors) =====================
roller_normal.add_event_cb(roller_week_cb, lv.EVENT.VALUE_CHANGED, None)
roller_infinite.add_event_cb(roller_month_cb, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

18. Lists

API nameMeaningInput parametersReturn value
add_textAdd a plain text item to the list (commonly used for group titles, description text, etc.)txt: str (text content; a string must be passed)obj (the created text item object)
add_buttonAdd a button item to the list (pass None as the first argument for no icon; pass an icon object to display that icon)icon: Any (NoneType passed in tests, no-icon case); txt: str (button display text, string type)obj (the created button item object)
get_button_textGet the current display text of the specified button item in the listbtn: obj (the button item object returned by add_button must be passed)str (the button's display text string)
set_button_textDynamically change the display text of the specified button item in the listbtn: obj (the target button item object);
txt: str (new button display text, string type)
None (no return value)

18.1 Creating Simple Grouped Headings and Button Lists

The following code performs the following operations:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

#Create the list object
list_obj = lv.list(scr)
list_obj.set_size(300, 200)
list_obj.center()
#Add a text item
list_obj.add_text("button A")
#Add a button item
btnA1 = list_obj.add_button(None, "A1")
btnA2 = list_obj.add_button(None, "A2")
btnA3 = list_obj.add_button(None, "A3")
#Add a text item
list_obj.add_text("button B")
#Add a button item
btnB1 = list_obj.add_button(None, "B1")
btnB2 = list_obj.add_button(None, "B2")
btnB3 = list_obj.add_button(None, "B3")

# Load the screen
lv.screen_load(scr)

18.2 Reading and Dynamically Modifying Button List Text

In the code below, we have completed the following tasks:

  1. First, initialize the LVGL environment, set the screen background to solid black, and create a list object that is 300×200 pixels in size and displayed centered on the screen;
  2. Then, write dedicated click callback functions for the six buttons A1/A2/A3 and B1/B2/B3 respectively. In each callback, first get_button_text is used to read and print the original display text of the button, then set_button_text is used to dynamically modify the button text to a new text with the suffix "(Clicked)", and finally the modified text is read again and printed to verify the effect;
  3. Then add the group titles "button A" and "button B" to the list, create six buttons corresponding to the respective groups, and bind a dedicated callback function to each button.
  4. The final loading screen applies the configuration.

After running the program, click any button, and the Console will output the English text information of the button before and after modification, while the button text on the interface will also be updated synchronously.

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the list object (global, for use by callbacks)
list_obj = lv.list(scr)
list_obj.set_size(300, 200)
list_obj.center()

# ===================== Dedicated callback for each button (demonstrates get/set_button_text) =====================
# Dedicated callback for button A1: full demonstration of get/set_button_text usage
def on_btnA1_click(e):
    # 1. Demonstrate get_button_text: read the text currently displayed on the button
    original_text = list_obj.get_button_text(btnA1)
    print(f"[A1] Original text: {original_text}")
    
    # 2. Demonstrate set_button_text: dynamically change the button text
    list_obj.set_button_text(btnA1, "A1 (Clicked)")
    
    # 3. Verify the change: read the button text again
    updated_text = list_obj.get_button_text(btnA1)
    print(f"[A1] Updated text: {updated_text}\n")

# Dedicated callback for button A2
def on_btnA2_click(e):
    original_text = list_obj.get_button_text(btnA2)
    print(f"[A2] Original text: {original_text}")
    list_obj.set_button_text(btnA2, "A2 (Clicked)")
    updated_text = list_obj.get_button_text(btnA2)
    print(f"[A2] Updated text: {updated_text}\n")

# Dedicated callback for button A3
def on_btnA3_click(e):
    original_text = list_obj.get_button_text(btnA3)
    print(f"[A3] Original text: {original_text}")
    list_obj.set_button_text(btnA3, "A3 (Clicked)")
    updated_text = list_obj.get_button_text(btnA3)
    print(f"[A3] Updated text: {updated_text}\n")

# Dedicated callback for button B1
def on_btnB1_click(e):
    original_text = list_obj.get_button_text(btnB1)
    print(f"[B1] Original text: {original_text}")
    list_obj.set_button_text(btnB1, "B1 (Clicked)")
    updated_text = list_obj.get_button_text(btnB1)
    print(f"[B1] Updated text: {updated_text}\n")

# Dedicated callback for button B2
def on_btnB2_click(e):
    original_text = list_obj.get_button_text(btnB2)
    print(f"[B2] Original text: {original_text}")
    list_obj.set_button_text(btnB2, "B2 (Clicked)")
    updated_text = list_obj.get_button_text(btnB2)
    print(f"[B2] Updated text: {updated_text}\n")

# Dedicated callback for button B3
def on_btnB3_click(e):
    original_text = list_obj.get_button_text(btnB3)
    print(f"[B3] Original text: {original_text}")
    list_obj.set_button_text(btnB3, "B3 (Clicked)")
    updated_text = list_obj.get_button_text(btnB3)
    print(f"[B3] Updated text: {updated_text}\n")

# ===================== Create the list content and bind the dedicated callbacks =====================
# Add a text item (group title)
list_obj.add_text("button A")
# Create the group A buttons and bind the callbacks
btnA1 = list_obj.add_button(None, "A1")
btnA1.add_event_cb(on_btnA1_click, lv.EVENT.CLICKED, None)

btnA2 = list_obj.add_button(None, "A2")
btnA2.add_event_cb(on_btnA2_click, lv.EVENT.CLICKED, None)

btnA3 = list_obj.add_button(None, "A3")
btnA3.add_event_cb(on_btnA3_click, lv.EVENT.CLICKED, None)

# Add a text item (group title)
list_obj.add_text("button B")
# Create the group B buttons and bind the callbacks
btnB1 = list_obj.add_button(None, "B1")
btnB1.add_event_cb(on_btnB1_click, lv.EVENT.CLICKED, None)

btnB2 = list_obj.add_button(None, "B2")
btnB2.add_event_cb(on_btnB2_click, lv.EVENT.CLICKED, None)

btnB3 = list_obj.add_button(None, "B3")
btnB3.add_event_cb(on_btnB3_click, lv.EVENT.CLICKED, None)

# Load the screen
lv.screen_load(scr)

19. Tabs

API namePurposeInput parametersReturn value
add_tabAdd a new tab to the tab viewstr (display name of the tab; must be a string)obj (the created tab object)
rename_tabRename the specified tab by its position indexint (tab position index, starting from 0); str (new display name of the tab)None (no return value)
set_activeSet the tab at the specified index as active, and control whether the switch is animatedint (target tab index, starting from 0);
int (animation switch, lv.ANIM.OFF=0/ON=1)
None (no return value)
set_tab_bar_positionSet the position of the tab bar (top / bottom / left / right)int (position enum value, lv.DIR.TOP=0/BOTTOM=1/LEFT=2/RIGHT=3)None (no return value)
set_tab_bar_sizeSet the size of the tab bar (in pixels)int (tab bar size in pixels; must be a positive integer)None (no return value)
get_tab_countGet the total number of tabs in the tab viewNo parametersint (total number of tabs)
get_tab_activeGet the index of the currently active tabNo parametersint (active tab index, starting from 0)
get_contentGet the content area object of the tab view (used to add widgets to a tab)No parametersobj (content area object)
get_tab_barGet the tab bar object of the tab view (used to customize the tab bar style)No parametersobj (tab bar object)

19.1 Basic Tab

In the following code, we implement a basic tab view control:

  1. First, initialize the LVGL environment, obtain the currently active screen object, and set its background color to black;
  2. Then create a tab view control on the screen, and add three tabs "A", "B" and "C" to it;
  3. Then create label controls for each tab respectively, set the label text to "tabview A", "tabview B", and "tabview C" in sequence, and center the labels;

The final loading screen applies all configurations, ultimately presenting a view with three tabs on a black-background screen; clicking different tabs will display the corresponding label text centered on the screen.

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

#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 tab view
tabview = lv.tabview(scr)
#Add tabs
tab1 = tabview.add_tab("A")
tab2 = tabview.add_tab("B")
tab3 = tabview.add_tab("C")
#Add tab content
label1 = lv.label(tab1)
label1.set_text("tabview A")
label1.center()
label2 = lv.label(tab2)
label2.set_text("tabview B")
label2.center()
label3 = lv.label(tab3)
label3.set_text("tabview C")
label3.center()

# Load the screen
lv.screen_load(scr)
v9.0

19.2 Get the active tab and set the default active option

In the following code, we add a tab switching event, and in the callback function, we obtain and print the index of the currently active tab in real time; by default, the tab with index 2 is activated during initialization.

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the tab view and add tabs
tabview = lv.tabview(scr)
tab1 = tabview.add_tab("A")
tab2 = tabview.add_tab("B")
tab3 = tabview.add_tab("C")

# Add content to the tabs
label1 = lv.label(tab1)
label1.set_text("tabview A")
label1.center()
label2 = lv.label(tab2)
label2.set_text("tabview B")
label2.center()
label3 = lv.label(tab3)
label3.set_text("tabview C")
label3.center()

# ===================== Define the event callback function =====================
def on_tab_switch(e):
    """Tab switch event callback: get and print the index of the currently active tab"""
    # Get the index of the currently active tab
    active_idx = tabview.get_tab_active()
    print(f"Current active tab index: {active_idx}")

# Bind the tab switch event (LV_EVENT.VALUE_CHANGED means the tab was switched)
tabview.add_event_cb(on_tab_switch, lv.EVENT.VALUE_CHANGED, None)

# Initially set the tab at index 2 as active (animation off), which triggers the switch event and prints the index
tabview.set_active(2, lv.ANIM.OFF)

# Load the screen
lv.screen_load(scr)
v9.0 2
0 1 2

19.3 Dynamically rename tabs and print the total number of tabs

In the following code, we add a tab click event: only when the tab at index 1 (Tab B) is clicked will the rename operation be executed, and the total number of tabs will be printed.

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the tab view and add tabs
tabview = lv.tabview(scr)
tab1 = tabview.add_tab("A")
tab2 = tabview.add_tab("B")
tab3 = tabview.add_tab("C")

# Add content to the tabs
label1 = lv.label(tab1)
label1.set_text("tabview A")
label1.center()
label2 = lv.label(tab2)
label2.set_text("tabview B")
label2.center()
label3 = lv.label(tab3)
label3.set_text("tabview C")
label3.center()

# Flag whether it has been renamed (avoid repeated triggering)
renamed_flag = False

# ===================== Define the event callback function =====================
def on_tab_click(e):
    """Tab click event callback: rename the tab at index 1 when it is clicked"""
    global renamed_flag
    # Get the index of the currently active tab
    active_idx = tabview.get_tab_active()
    
    # Rename only when the tab at index 1 is clicked and it has not been renamed yet
    if active_idx == 1 and not renamed_flag:
        # Rename the tab at index 1 to "B (Renamed)"
        tabview.rename_tab(1, "B (Renamed)")
        # Get the total number of tabs and print it
        total_tabs = tabview.get_tab_count()
        print(f"Tab index 1 renamed to 'B (Renamed)', total tabs: {total_tabs}")
        renamed_flag = True  # Mark as renamed

# Bind the tab switch/click event
tabview.add_event_cb(on_tab_click, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)
19.4
1 3

19.4 Dynamically modify the position and size of the tab bar by clicking tabs

In the following code, we add an event callback: only when the tab at index 2 (Tab C) is clicked, set the tab bar position to the bottom, set its size to 50 pixels, and print a prompt message.

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the tab view and add tabs
tabview = lv.tabview(scr)
tab1 = tabview.add_tab("A")
tab2 = tabview.add_tab("B")
tab3 = tabview.add_tab("C")

# Add content to the tabs
label1 = lv.label(tab1)
label1.set_text("tabview A")
label1.center()
label2 = lv.label(tab2)
label2.set_text("tabview B")
label2.center()
label3 = lv.label(tab3)
label3.set_text("tabview C")
label3.center()

# Flag whether it has been set (avoid repeated triggering)
set_flag = False

# ===================== Define the event callback function =====================
def on_tab_click(e):
    """Tab click event callback: set the tab bar properties when the tab at index 2 is clicked"""
    global set_flag
    # Get the index of the currently active tab
    active_idx = tabview.get_tab_active()
    
    # Modify the properties only when the tab at index 2 is clicked and it has not been set yet
    if active_idx == 2 and not set_flag:
        # Set the tab bar position to the bottom
        tabview.set_tab_bar_position(lv.DIR.BOTTOM)
        # Set the tab bar size to 50 pixels
        tabview.set_tab_bar_size(50)
        # Print a prompt message
        print("Tab bar position set to BOTTOM, size set to 50px")
        set_flag = True  # Mark as set

# Bind the tab switch/click event
tabview.add_event_cb(on_tab_click, lv.EVENT.VALUE_CHANGED, None)

# Load the screen
lv.screen_load(scr)

19.5 Obtain the content area and tab bar object and customize the style

In the following code, we take the tab bar object and change its background color to gray; all operations will print the object type and style modification prompts via the Console, and after the screen is finally loaded, you can intuitively see that the tab bar has turned gray:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create the tab view and add tabs
tabview = lv.tabview(scr)
tab1 = tabview.add_tab("A")
tab2 = tabview.add_tab("B")
tab3 = tabview.add_tab("C")

# Add content to the tabs
label1 = lv.label(tab1)
label1.set_text("tabview A")
label1.center()
label2 = lv.label(tab2)
label2.set_text("tabview B")
label2.center()
label3 = lv.label(tab3)
label3.set_text("tabview C")
label3.center()

# ===================== Demonstrate the get_content and get_tab_bar APIs =====================
# 1. Get the content area object of the tab view and print its type
content_area = tabview.get_content()
print(f"Tabview content area object type: {type(content_area).__name__}")  # Output: obj
# 2. Get the tab bar object and set its background color to gray (0x808080)
tab_bar = tabview.get_tab_bar()
tab_bar.set_style_bg_color(lv.color_hex(0x808080), 0)
print("Tab bar background color set to gray")  # Note that the tab bar background color has been changed

# Load the screen
lv.screen_load(scr)
03 Quick Start Example - Control Section (Based on Web Simulator and LVGL v9.0)

20. Menu

There are currently some issues with this control.

21. Tables

API nameCore functionInput parametersReturn valueNotes (SDL environment behavior)
set_cell_valueSet the text content of the specified cellrow: row number (int),
col: column number (int),
txt: cell text (str)
No return value (NoneType)Numeric arguments accept only int; str triggers a type error
set_row_countSet the total number of rows of the tablecount: total number of rows (int)No return value (NoneType)Passing too few / too many arguments triggers an argument count error
set_column_countSet the total number of columns of the tablecount: total number of columns (int)No return value (NoneType)A float argument triggers a type error
set_column_widthSet the width of the specified columncol_id: column index (int), w: column width (int)No return value (NoneType)Width must be a positive integer
add_cell_ctrlSet control attributes for the specified cell (replaces set_cell_ctrl)row: row number (int),
col: column number (int),
ctrl: control attribute (int, e.g. CELL_CTRL.TEXT_CROP)
No return value (NoneType)ctrl must be a CELL_CTRL enum value (int type)
clear_cell_ctrlClear the control attributes of the specified cellrow: row number (int),
col: column number (int),
ctrl: control attribute (int)
No return value (NoneType)Passing extra arguments triggers an argument count error
set_cell_user_dataBind a custom user data object to the specified cellrow: row number (int),
col: column number (int),
obj: user data object (lv.obj)
No return value (NoneType)SDL allows passing str, but it has no effect
get_cell_valueGet the text content of the specified cellrow: row number (int),
col: column number (int)
cell_text: cell text (str)Returns an empty string if not set
get_row_countGet the total number of rows of the tableNonerow_count: total number of rows (int)Returns the default value (e.g. 0) if not set
get_column_countGet the total number of columns of the tableNonecol_count: total number of columns (int)Returns the default value (e.g. 0) if not set
get_column_widthGet the width of the specified columncol: column index (int)col_width: column width (int)Returns the default width if not set
has_cell_ctrlCheck whether the specified cell has the target control attributerow: row number (int),
col: column number (int),
ctrl: control attribute (int)
is_has: whether the cell has the attribute (bool)Returning False means the attribute is not set
get_selected_cellGet the currently selected cell position (the result is stored in the passed-in lists)row_list: list that receives the selected row number (list), col_list: list that receives the selected column number (list)No return value (NoneType); the result is stored in the passed-in listsSDL allows passing str, but it cannot receive the result
get_cell_user_dataGet the user data object bound to the specified cellrow: row number (int),
col: column number (int)
user_data: user data object (Blob/lv.obj)Displayed as Blob type in the SDL environment

21.1 Basic Table

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# 1. Create table instance
table = lv.table(scr)
table.set_size(300, 200)  # Set table size
table.align(lv.ALIGN.CENTER, 0, 0)  # Center on screen
# Set number of table rows and columns
table.set_row_count(4)
table.set_column_count(3)
# Set column width
table.set_column_width(0, 80)
table.set_column_width(1, 100)

# Fill table data
table.set_cell_value(0, 0, "ID")
table.set_cell_value(0, 1, "NAME")
table.set_cell_value(0, 2, "STATE")

table.set_cell_value(1, 0, "001")
table.set_cell_value(1, 1, "Device A")
table.set_cell_value(1, 2, "ON")

table.set_cell_value(2, 0, "002")
table.set_cell_value(2, 1, "Device B")
table.set_cell_value(2, 2, "OFF")

table.set_cell_value(3, 0, "003")
table.set_cell_value(3, 1, "Device C")
table.set_cell_value(3, 2, "ON")

# Load the screen
lv.screen_load(scr)
v9.0 001 002 003

21.2 Get the total number of rows in a table and the width of a specified column

# get_row_count: query total number of table rows
current_row_count = table.get_row_count()
print(f"get_row_count() → Current total rows: {current_row_count}, return value type: {type(current_row_count).__name__}")

# get_column_width: query width of specified column
query_col_width = 1
current_col_width = table.get_column_width(query_col_width)
print(f"get_column_width({query_col_width}) → Width of column {query_col_width}: {current_col_width}, return value type: {type(current_col_width).__name__}")
v9.0 001 21.1

21.3 Add Cell Control Properties

Cell control attribute (CELL_CTRL) is the display/behavior rule provided by LVGL for table cells, defined via enumeration values (such as text clipping, cell merging, custom markers, etc.), which is used to control the rendering logic and interaction behavior of cells.

In the following code, the following operations are performed:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# Create table instance and initialize basic configuration
table = lv.table(scr)
table.set_size(400, 250)  # Enlarge table size to make merge/crop effects easier to show
table.align(lv.ALIGN.CENTER, 0, 0)
table.set_row_count(4)
table.set_column_count(3)
table.set_column_width(0, 80)
table.set_column_width(1, 100)
table.set_column_width(2, 80)

# Purpose: disable vertical scrolling of the table and let height adapt automatically, avoiding an initial scrollbar
table.set_scroll_dir(lv.DIR.NONE) 

# Fill test data (includes long text to demonstrate the TEXT_CROP effect)
table.set_cell_value(0, 0, "ID")
table.set_cell_value(0, 1, "NAME")
table.set_cell_value(0, 2, "STATE")
table.set_cell_value(1, 0, "001")
table.set_cell_value(1, 1, "Device A - Long Text For Crop Test")  # Very long text
table.set_cell_value(1, 2, "ON")
table.set_cell_value(2, 0, "002")
table.set_cell_value(2, 1, "Device B")
table.set_cell_value(2, 2, "OFF")

# Control attribute 1: TEXT_CROP - crop text when too long (the part beyond the column width is hidden)
# Purpose: prevent very long text from stretching the cell, showing only content within the column width
crop_row, crop_col = 1, 1
crop_ctrl = lv.table.CELL_CTRL.TEXT_CROP
# Add TEXT_CROP attribute
table.add_cell_ctrl(crop_row, crop_col, crop_ctrl)
print(f"add_cell_ctrl({crop_row},{crop_col},TEXT_CROP) → Add text crop attribute, return value: None")
# Check whether it was added successfully
is_has_crop = table.has_cell_ctrl(crop_row, crop_col, crop_ctrl)
print(f"has_cell_ctrl({crop_row},{crop_col},TEXT_CROP) → Attribute exists: {is_has_crop}, return type: {type(is_has_crop).__name__}")

# Control attribute 2: MERGE_RIGHT - merge cell to the right (the current cell merges with the column to its right)
# Purpose: merge adjacent cells to achieve a column-spanning display
merge_row, merge_col = 3, 0
merge_ctrl = lv.table.CELL_CTRL.MERGE_RIGHT
# First fill in the text of the merged cell
table.set_cell_value(merge_row, merge_col, "Merged Cell (003+Device C)")
# Add MERGE_RIGHT attribute (merge columns 0 and 1 of row 3)
table.add_cell_ctrl(merge_row, merge_col, merge_ctrl)
print(f"add_cell_ctrl({merge_row},{merge_col},MERGE_RIGHT) → Add cell merge right attribute, return value: None")
# Check whether it was added successfully
is_has_merge = table.has_cell_ctrl(merge_row, merge_col, merge_ctrl)
print(f"has_cell_ctrl({merge_row},{merge_col},MERGE_RIGHT) → Attribute exists: {is_has_merge}, return type: {type(is_has_merge).__name__}")

# Purpose: force LVGL to recalculate the table layout, avoiding an initial scrollbar/line-wrap anomalies
table.update_layout()

# Load screen (shows the effect of TEXT_CROP cropping long text and MERGE_RIGHT merging cells)
lv.screen_load(scr)
001 002
001 002 003 004 003+Device

22. Displaying Images and Animated GIFs

The summary table of core APIs for lv.image is as follows:

API nameMeaningInput arguments (count + type + description)Return value (type + description)
set_rotationSet the image rotation angle1, int type (rotation angle, e.g. 90/180/270)None, no return value
get_rotationGet the current image rotation angle0, no input argumentsint type (current rotation angle value)
set_srcSet the image source (file / symbol / binary data)1, str type (image path such as "test.png" or an LVGL built-in symbol)None, no return value
set_offset_xSet the image X-axis offset (horizontal position adjustment)1, int type (offset in pixels; positive shifts right, negative shifts left)None, no return value
get_offset_xGet the current image X-axis offset0, no input argumentsint type (current X-axis offset in pixels)
set_offset_ySet the image Y-axis offset (vertical position adjustment)1, int type (offset in pixels; positive shifts down, negative shifts up)None, no return value
get_offset_yGet the current image Y-axis offset0, no input argumentsint type (current Y-axis offset in pixels)
set_scaleSet the overall image zoom ratio (proportional scaling)1, int type (zoom ratio, 100=100%, 200=200%)None, no return value
get_scaleGet the current overall image zoom ratio0, no input argumentsint type (current overall zoom ratio value)
set_scale_xSet the image X-axis zoom ratio separately (width scaling only)1, int type (X-axis zoom ratio)None, no return value
get_scale_xGet the current image X-axis zoom ratio0, no input argumentsint type (current X-axis zoom ratio value)
set_scale_ySet the image Y-axis zoom ratio separately (height scaling only)1, int type (Y-axis zoom ratio)None, no return value
get_scale_yGet the current image Y-axis zoom ratio0, no input argumentsint type (current Y-axis zoom ratio value)
set_antialiasEnable / disable image anti-aliasing (smooths scaled / rotated edges)1, bool type (True to enable, False to disable)None, no return value
get_antialiasCheck whether image anti-aliasing is enabled0, no input argumentsbool type (True = enabled, False = disabled)
set_blend_modeSet the image blend mode (transparency / overlay effects, etc.)1, lv.blend_mode_t enum (e.g. lv.BLEND_MODE.NORMAL)None, no return value
get_blend_modeGet the current image blend mode0, no input argumentslv.blend_mode_t enum (current blend mode)
set_pivotSet the image rotation pivot point2, int type (x: pivot X coordinate, y: pivot Y coordinate)None, no return value
get_pivotGet the image rotation pivot point1, lv.point_t object (used to receive the pivot coordinates)None, the result is stored in the passed-in lv.point_t object

The summary table of core APIs for lv.image is as follows:

API nameMeaningInput parametersReturn valueTypical exception messages in the SDL environment
set_srcSet the GIF source (file / binary data)Count: 1 Type: str/bytes Description: str = GIF file path (e.g. "anim.gif"); bytes = GIF binary dataCount: 0 Type: None Description: No return value1. Wrong argument count: argument num/types mismatch 2. Wrong type (int passed): Cannot convert 'int' to pointer!
restartRestart GIF playback (play from the beginning)Count: 0 Type: None Description: No arguments neededCount: 0 Type: None Description: No return valuePassing any argument: argument num/types mismatch
pausePause GIF playbackCount: 0 Type: None Description: No arguments neededCount: 0 Type: None Description: No return valuePassing any argument: argument num/types mismatch
resumeResume GIF playback (continue after pause)Count: 0 Type: None Description: No arguments neededCount: 0 Type: None Description: No return valuePassing any argument: argument num/types mismatch

The summary table of LVGL built-in symbols (SYMBOL) is shown below, which organizes the name, meaning, type and typical usage scenarios of LVGL built-in symbols (lv.SYMBOL) by function, to adapt to the development requirements of SDL LVGL/MicroPython environment, and all symbol types are int (can be directly passed to interfaces such as lv.image.set_src / button text):

CategorySymbol nameMeaningTypeTypical Use Case
Basic identifiersSYMBOL.BULLETDot / bulletintList item prefix, marker dot
Basic identifiersSYMBOL.LISTListintList menu entry, list view icon
Basic identifiersSYMBOL.OKConfirm / checkmarkintSubmit button, operation success indicator
Basic identifiersSYMBOL.CLOSEClose / crossintClose button, cancel operation, popup close
Basic identifiersSYMBOL.WARNINGWarning / exclamation markintError indication, risky operation reminder
MultimediaSYMBOL.AUDIOAudio / soundintAudio playback entry, sound settings
MultimediaSYMBOL.VIDEOVideointVideo playback entry, video settings
MultimediaSYMBOL.MUTEMuteintMute button, volume off
MultimediaSYMBOL.VOLUME_MIDMedium volumeintVolume adjustment (medium)
MultimediaSYMBOL.VOLUME_MAXMaximum volumeintVolume adjustment (maximum)
MultimediaSYMBOL.PREVPrevious track / previous frameintMedia playback control (previous)
MultimediaSYMBOL.PLAYPlayintPlay button, start animation
MultimediaSYMBOL.PAUSEPauseintPause button, pause animation
MultimediaSYMBOL.STOPStopintStop button, stop playback
MultimediaSYMBOL.NEXTNext track / next frameintMedia playback control (next)
MultimediaSYMBOL.EJECTEject / exitintDisc eject, device exit
MultimediaSYMBOL.SHUFFLEShuffleintMedia shuffle mode
MultimediaSYMBOL.LOOPRepeatintMedia repeat mode
Navigation / directionSYMBOL.LEFTLeft arrowintBack, move left, previous step
Navigation / directionSYMBOL.RIGHTRight arrowintForward, move right, next step
Navigation / directionSYMBOL.UPUp arrowintMove up, scroll up, increase
Navigation / directionSYMBOL.DOWNDown arrowintMove down, scroll down, decrease
Operation / controlSYMBOL.POWERPower supplyintPower on / off button, power status
Operation / controlSYMBOL.SETTINGSSettingsintSettings entry, configuration menu
Operation / controlSYMBOL.HOMEHomeintReturn to home button
Operation / controlSYMBOL.REFRESHRefresh / reloadintRefresh data, reload page
Operation / controlSYMBOL.PLUSPlus signintIncrease, add, create new
Operation / controlSYMBOL.MINUSMinus signintDecrease, delete, remove
Operation / controlSYMBOL.EYE_OPENEye (open)intShow password, show hidden content
Operation / controlSYMBOL.EYE_CLOSEEye (closed)intHide password, hide sensitive content
Operation / controlSYMBOL.CUTCutintText / file cut operation
Operation / controlSYMBOL.COPYCopyintText / file copy operation
Operation / controlSYMBOL.PASTEPasteintText / file paste operation
Operation / controlSYMBOL.SAVESaveintSave file, save configuration
Operation / controlSYMBOL.EDITEditintEdit text, modify content
Operation / controlSYMBOL.BACKSPACEBackspace / deleteintKeyboard backspace, delete character
Operation / controlSYMBOL.NEW_LINENewlineintKeyboard newline, text line break
File / storageSYMBOL.DOWNLOADDownloadintFile download, data import
File / storageSYMBOL.UPLOADUploadintFile upload, data export
File / storageSYMBOL.DRIVEDrive / diskintDisk / drive entry
File / storageSYMBOL.DIRECTORYFolder / directoryintFolder entry, directory browsing
File / storageSYMBOL.FILEFileintFile icon, file list item
File / storageSYMBOL.TRASHRecycle bin / deleteintDelete file, empty recycle bin
File / storageSYMBOL.SD_CARDSD cardintSD card storage, external storage entry
Device / connectionSYMBOL.CALLPhone / callintMake a call, call log
Device / connectionSYMBOL.WIFIWIFIintWIFI status, network settings
Device / connectionSYMBOL.BLUETOOTHBluetoothintBluetooth status, Bluetooth settings
Device / connectionSYMBOL.USBUSBintUSB connection, USB storage
Device / connectionSYMBOL.GPSPositioning / GPSintLocation service, map navigation
Status / promptSYMBOL.BARSProgress bar / bar chartintProgress display, data statistics
Status / promptSYMBOL.ENVELOPEEnvelope / mailintMail notification, message center
Status / promptSYMBOL.CHARGEChargingintDevice charging status, charging prompt
Status / promptSYMBOL.BELLBell / notificationintMessage notification, reminder settings
Status / promptSYMBOL.BATTERY_FULLBattery (full)intBattery full status
Status / promptSYMBOL.BATTERY_3Battery (3/4)intBattery 75% charge status
Status / promptSYMBOL.BATTERY_2Battery (2/4)intBattery 50% charge status
Status / promptSYMBOL.BATTERY_1Battery (1/4)intBattery 25% charge status
Status / promptSYMBOL.BATTERY_EMPTYBattery (empty)intBattery low / dead status
Image / editSYMBOL.IMAGEPicture / imageintImage viewing, gallery entry
Image / editSYMBOL.TINTColor adjustment / coloringintImage color adjustment, color settings
Input / interactionSYMBOL.KEYBOARDKeyboardintVirtual keyboard, input entry
Placeholder / testSYMBOL.DUMMYPlaceholder / testintUI placeholder, function test

LVGL Blend Mode lv.BLEND_MODE Names, descriptions, blending effects and typical use cases of all enumeration values:

Symbol nameMeaningTypeBlend effect descriptionTypical Use Case
BLEND_MODE.NORMALNormal blendintDefault mode, foreground pixels cover background pixels (background shows only in transparent areas), no color overlay / modificationNormal display (icons, text, regular images, buttons)
BLEND_MODE.ADDITIVEAdditive blendintForeground color + background color (brightness adds up, colors get brighter as they mix, white + any color = white)Glow effect (button highlight, notification prompt, light animation, gradient glow)
BLEND_MODE.SUBTRACTIVESubtractive blendintBackground color - foreground color (brightness decreases, colors get darker as they mix, black - any color = black)Shadow effects, mask overlays, vignette processing, reducing local brightness
BLEND_MODE.MULTIPLYMultiplyintForeground color × background color (colors darken, contrast increases, white × any color = original background color)Image overlay, texture blending, dark watermarks, retro filters
BLEND_MODE.DIFFERENCEDifference blendintDifference between the pixel values of the foreground and background colors (colors invert, strong contrast, same color = black)Color inversion effects, difference marking, warning alerts, contrast highlighting

22.1 Basic Display of Images and GIFs

import display_driver
import lvgl as lv
import fs_driver

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)

fs_drv = lv.fs_drv_t()
fs_driver.fs_register(fs_drv, 'S')

'''Display LVGL built-in symbols'''
# Create image
img_symbol = lv.image(scr)
# Display an LVGL built-in symbol ("AUDIO" icon); for more icons see the "class SYMBOL" section of api.py
img_symbol.set_src(lv.SYMBOL.AUDIO)
#Center it
img_symbol.align(lv.ALIGN.CENTER, 0, 0)

# The code below cannot be displayed in the simulator!!!

# '''Display images from storage'''
# img_symbol2 = lv.image(scr)
# # Display png
# img_symbol2.set_src('S:001.png')
# # Display jpg
# #img_symbol2.set_src('S:001.jpg')
# img_symbol2.align(lv.ALIGN.RIGHT_MID, 0, 0)  # Display on the right

# '''Display gif'''
# img_symbol3 = lv.gif(scr)
# img_symbol3.set_src('S:001.gif')
# img_symbol3.align(lv.ALIGN.LEFT_MID, 0, 0)  # Display on the left

# Load the screen
lv.screen_load(scr)
v9.0 22.1

22.2 Internal Icon Display

The code is as follows:

import display_driver
import lvgl as lv

# Initialize the LVGL environment
lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)  # White background

# ========== 1. Core parameter configuration (adjustable, controls density/size) ==========
ICON_SIZE = 24          # Size of a single icon (width = height; smaller shows more)
ICON_GAP = 8            # Spacing between icons (horizontal/vertical)
SCREEN_PADDING = 8      # Padding at screen edges (keeps icons from touching the edge)

# ========== 2. Get all built-in SYMBOL icons ==========
symbol_list = [
    getattr(lv.SYMBOL, name)
    for name in dir(lv.SYMBOL)
    if not name.startswith("__") and name.isupper()
]
total_icons = len(symbol_list)
print(f"Total icons: {total_icons}")

# ========== 3. Dynamically calculate layout (adapts to any screen size) ==========
# Get actual screen size (automatically adapted in the SDL environment)
screen_w = scr.get_width()
screen_h = scr.get_height()

# Calculate the number of icons that fit per row/column
icons_per_row = (screen_w - 2 * SCREEN_PADDING) // (ICON_SIZE + ICON_GAP)
icons_per_col = (screen_h - 2 * SCREEN_PADDING) // (ICON_SIZE + ICON_GAP)
max_icons_per_screen = icons_per_row * icons_per_col
print(f"Screen size: {screen_w}x{screen_h}")
print(f"Icons per row: {icons_per_row}, per column: {icons_per_col}")
print(f"Max icons per screen: {max_icons_per_screen}")

# ========== 4. Manual layout: create icons one by one and set coordinates ==========
for idx, sym in enumerate(symbol_list):
    # Skip the part beyond one screen (to show all, add scrolling; see the extension below)
    if idx >= max_icons_per_screen:
        break
    
    # Calculate the row/column of the current icon
    row = idx // icons_per_row
    col = idx % icons_per_row
    
    # Calculate icon coordinates (core formula for even distribution)
    x = SCREEN_PADDING + col * (ICON_SIZE + ICON_GAP)
    y = SCREEN_PADDING + row * (ICON_SIZE + ICON_GAP)
    
    # Create icon (directly as a child of the screen, no container)
    img = lv.image(scr)
    img.set_size(ICON_SIZE, ICON_SIZE)  # Fixed size
    img.set_src(sym)                    # Set SYMBOL icon
    img.set_pos(x, y)                   # Set coordinates manually

# ========== 5. Load screen ==========
lv.screen_load(scr)
62 12 9 10

Version Record

Version Number

Modifier

Time

Content

v1.0

Li Zisheng

2026/03/13

Initialize the document.