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

如何修改Gradio对话气泡文本框的背景色?

修改Gradio Chatbot对话气泡背景色的可行方案

1. 替代弃用的color_map:用自定义Theme

Gradio 3.x版本后,style(color_map=...)已被官方弃用,现在推荐通过自定义Theme来设置消息气泡颜色:

import gradio as gr

# 自定义主题,分别设置用户和助手消息的背景色
custom_theme = gr.themes.Default(
    colors=gr.themes.Color(
        primary="#007bff",  # 用户消息背景色
        secondary="#28a745",  # 助手消息背景色
    )
)

with gr.Blocks(theme=custom_theme) as demo:
    chatbot = gr.Chatbot(elem_id="chat")
    # 这里添加你的输入框、按钮等组件

demo.launch()

2. 修复外部CSS无效问题:精准类选择器

之前用elem_id设置CSS没生效,是因为Gradio的Chatbot气泡有专属类名,需要用更精准的选择器覆盖默认样式:
先写CSS代码:

/* 用户发送的消息气泡 */
#chat .user {
    background-color: blue !important;
}

/* 助手回复的消息气泡 */
#chat .bot {
    background-color: green !important;
}

然后在Gradio中引入:
如果是外部CSS文件,这样加载:

with gr.Blocks(css="your_style.css") as demo:
    chatbot = gr.Chatbot(elem_id="chat")
    # 其他组件逻辑

也可以直接内联CSS,不用单独文件:

css_code = """
#chat .user {
    background-color: blue !important;
}
#chat .bot {
    background-color: green !important;
}
"""
with gr.Blocks(css=css_code) as demo:
    chatbot = gr.Chatbot(elem_id="chat")
    # 其他组件逻辑

加!important是为了强制覆盖Gradio自带的内联样式,避免优先级不够的问题。

3. 单个Chatbot组件单独设置(不影响全局)

如果不想修改全局主题,只想给这个Chatbot单独改色,可以直接在组件初始化时指定theme:

chatbot = gr.Chatbot(
    elem_id="chat",
    theme=gr.themes.Default(
        colors=gr.themes.Color(primary="blue", secondary="green")
    )
)

内容的提问来源于stack exchange,提问作者dark.vador

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:27:09