使用Streamlit与qrcode库时,color_mask接收颜色选择器输入报NoneType错误
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
Add a hex-to-RGB conversion function
Convert the hex code from Streamlit’s color picker to the (R, G, B) tuple format thatSolidFillColorMaskaccepts.Set default colors
Initialize the color pickers with default values to avoidNonewhen the app loads for the first time.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_rgbfunction handles hex codes with or without the#prefix (Streamlit’s picker always includes it, but addinglstrip('#')makes it robust). - Default values in
st.color_pickereliminate 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

