You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Streamlit与qrcode库时,color_mask接收颜色选择器输入报NoneType错误

Fix for Streamlit Color Picker with QRCode SolidFillColorMask

The core issue here is that st.color_picker returns a hex color string (e.g., #ffffff), but SolidFillColorMask requires RGB integer tuples (values between 0-255). The NoneType error usually occurs either because you’re not converting the hex string to RGB, or you’re not handling the initial state where the color picker might return None before the user selects a color.

Step-by-Step Solutions

  1. Add a hex-to-RGB conversion function
    Convert the hex code from Streamlit’s color picker to the (R, G, B) tuple format that SolidFillColorMask accepts.

  2. Set default colors
    Initialize the color pickers with default values to avoid None when the app loads for the first time.

  3. Integrate conversion into your workflow
    Replace hardcoded RGB values with the converted results from the color pickers.

Working Code Example

import streamlit as st
import qrcode
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers import RoundedModuleDrawer
from qrcode.image.styles.colormasks import SolidFillColorMask

def hex_to_rgb(hex_color):
    # Remove '#' prefix if present
    hex_color = hex_color.lstrip('#')
    # Convert 6-digit hex to RGB tuple
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

# Initialize color pickers with default values
back_color_hex = st.color_picker("Select Background Color", "#ffffff")
front_color_hex = st.color_picker("Select Foreground Color", "#ff6e00")

# Convert hex codes to RGB tuples
back_color_rgb = hex_to_rgb(back_color_hex)
front_color_rgb = hex_to_rgb(front_color_hex)

# Generate QR code base
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data("Your QR Code Content")
qr.make(fit=True)

# Create styled QR image with custom colors
qr_eyes_img = qr.make_image(
    image_factory=StyledPilImage,
    eye_drawer=RoundedModuleDrawer(radius_ratio=1.2),
    color_mask=SolidFillColorMask(back_color=back_color_rgb, front_color=front_color_rgb)
)

# Display the QR code in Streamlit
st.image(qr_eyes_img)

Key Notes

  • The hex_to_rgb function handles hex codes with or without the # prefix (Streamlit’s picker always includes it, but adding lstrip('#') makes it robust).
  • Default values in st.color_picker eliminate NoneType errors on app startup.
  • Ensure you add data to the QR code and call make(fit=True) before generating the styled image—missing this step can cause unexpected issues.

内容的提问来源于stack exchange,提问作者Talha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:12:08