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

如何调整Gradio ChatInterface布局,让聊天区域铺满剩余屏幕空间?

解决Gradio聊天区域无法延伸至屏幕底部的问题

问题背景

编写了如下Gradio脚本:

import requests
import gradio as gr
import json

def chat_response(message, history, response_limit):
    return f"You wrote: {message} and asked {response_limit}"

with gr.Blocks() as demo:
    gr.Markdown("# Data Query!")
    with gr.Row():
        with gr.Column(scale=3):
            response_limit = gr.Number(label="Response Limit", value=10, interactive=True)
        with gr.Column(scale=7):
            chat = gr.ChatInterface(fn=chat_response,additional_inputs=[response_limit])

demo.launch()

运行后聊天区域下方存在大量空白,窗口尺寸过小,希望让聊天区域延伸至屏幕底部。修改代码添加CSS指定#chatbot的flex-grow:1后,聊天框有所变大,但仍未铺满屏幕底部。

另外,最初未给自定义Chatbot添加render=False时,出现DuplicateBlockError,通过设置render=False解决了该问题。

完整解决方案

要实现聊天区域铺满屏幕底部,需要让整个布局的所有上层容器都设置为flex布局并占满可用高度,修改后的代码如下:

import requests
import gradio as gr
import json

def chat_response(message, history, response_limit):
    return f"You wrote: {message} and asked {response_limit}"

css = """
/* 让根容器和Gradio主容器占满视口高度 */
:root, .gradio-container {
    height: 100vh !important;
    margin: 0;
    padding: 0;
}

/* 让Row容器占满标题栏外的剩余高度 */
.row {
    height: calc(100vh - 80px) !important;
    display: flex !important;
    flex-direction: row !important;
}

/* 让Column容器使用垂直flex布局并占满高度 */
.col {
    display: flex !important;
    flex-direction: column !important;
    height: 100% !important;
}

/* 让聊天区域占满列内剩余空间 */
#chatbot {
    flex-grow: 1 !important;
    overflow: auto !important;
}

/* 调整ChatInterface容器为垂直flex布局 */
.gr-chatinterface {
    height: 100% !important;
    display: flex !important;
    flex-direction: column !important;
}
"""

with gr.Blocks(css=css) as demo:
    gr.Markdown("# Data Query!")
    with gr.Row():
        with gr.Column(scale=3):
            response_limit = gr.Number(label="Response Limit", value=10, interactive=True)
        with gr.Column(scale=7):
            chat = gr.ChatInterface(
                fn=chat_response,
                chatbot=gr.Chatbot(elem_id="chatbot", render=False),
                additional_inputs=[response_limit]
            )

demo.launch()

关键说明

  • :root, .gradio-container:设置根元素和Gradio主容器占满整个视口高度,消除默认边距与内边距。
  • .row:通过calc(100vh - 80px)计算高度,减去标题栏的占用空间,确保Row容器铺满剩余屏幕区域(可根据标题实际大小调整数值)。
  • .col:让Column容器采用垂直flex布局,保证内部元素能按垂直方向分配空间。
  • #chatbot:利用flex-grow:1让聊天区域占满Column内的剩余空间,overflow:auto保证内容过多时可滚动查看。
  • .gr-chatinterface:让ChatInterface本身使用flex布局,确保内部聊天窗口和输入框的空间分配合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:04:51