Streamlit Components 记录

Streamlit 基础介绍

Components

一些日后也许会用上的组件

在 Streamlit 中使用 P5.js

import streamlit.components.v1 as components
import streamlit as st
import numpy as np

st.title("Test P5 in Streamlit")

# https://cdn.jsdelivr.net/npm/p5@1.6.0/lib/p5.js
# https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js

def get_html_content(script):
    return  f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <script
        type="text/javascript"
        src="https://cdn.jsdelivr.net/npm/p5@1.6.0/lib/p5.js"
        ></script>
        <meta charset="utf-8" />
    </head>
    <body>
        <script>
        {script}
        </script>
    </body>
    </html>
    """

def build_script(basic,setup,draw):
    return basic + "\nfunction setup() {" + setup +"} \nfunction draw() {" + draw +"}"

c1,c2 = st.columns(2)
with c1:
    st.write("Intearctive P5 with Streamlit")
    color = st.color_picker("Color Picker","#F4A460")
    point = st.radio("Point",["rect","circle"],index=0)
    x = st.slider("x",50,200,100)
    y = st.slider("y",50,200,100)
    text = st.text_input("Text","Change This Text")
with c2:
    
    basic = """
    let x = 1;
    let direction = 1;
    let step = 1;
    """
    
    setup = """
    createCanvas(400, 400);
    x = 200;
    """
    draw = f"""
        background("{color}");
        fill(255);
        textSize(20);
        text("P5 JS in Streamlit", 20, 50);
        text("{text}", 20, 100);
        fill(255);
        ellipse(x, 200, {x},{y});
        x = x + step * direction;
        if (x > 400 || x < 0) {{
            direction = -direction;
        }}
    """
    
    shapes = {
    "circle": "circle(mouseX,mouseY,10);",
    "rect": "rect(mouseX,mouseY,10,10);"
    }

    draw += shapes.get(point, "circle(mouseX,mouseY,10);")
    
    html_content = get_html_content(build_script(basic,setup,draw))
    
    print(html_content)
    
    components.html(html_content,width=400,height=400)

参考