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

如何在Gradio应用中实现查询触发的文本与对应图片联动输出?

解决方案

要实现输入查询后输出4组文本+对应图片的Gradio应用,需对现有代码做以下核心修改:

关键调整点

  1. 让处理函数同时返回4个文本内容和对应的4个图片路径
  2. 新增gr.Image组件作为输出,与文本组件一一对应
  3. 保证输出组件的顺序和返回值的顺序完全匹配

方法一:Interface模式(简单线性输出)

适合不需要复杂布局的场景,直接按顺序输出所有组件:

import gradio as gr

def gradio_fn(query):
    content, image_paths = answer_question(query)
    # 按文本1、图片1、文本2、图片2的顺序返回结果
    return content[0], image_paths[0], content[1], image_paths[1], content[2], image_paths[2], content[3], image_paths[3]

# 构建4组文本+图片的输出组件
output_components = [
    gr.Textbox(label="结果1 文本"), gr.Image(label="结果1 图片"),
    gr.Textbox(label="结果2 文本"), gr.Image(label="结果2 图片"),
    gr.Textbox(label="结果3 文本"), gr.Image(label="结果3 图片"),
    gr.Textbox(label="结果4 文本"), gr.Image(label="结果4 图片")
]

input_text = gr.Textbox(label="输入查询")
demo = gr.Interface(
    fn=gradio_fn,
    inputs=input_text,
    outputs=output_components
)

demo.launch(share=True)

方法二:Blocks模式(灵活布局)

如果需要更美观的分组布局(比如每组文本和图片上下排列),推荐使用Blocks模式:

import gradio as gr

def gradio_fn(query):
    content, image_paths = answer_question(query)
    return content, image_paths

with gr.Blocks(title="查询结果展示") as demo:
    gr.Markdown("# 输入查询获取图文结果")
    input_box = gr.Textbox(label="请输入查询内容", placeholder="在这里输入查询...")
    submit_btn = gr.Button("提交查询", variant="primary")
    
    # 创建4个并列的结果列,每列包含文本和图片
    with gr.Row():
        result_components = []
        for i in range(4):
            with gr.Column():
                result_components.append(gr.Textbox(label=f"第{i+1}组文本", interactive=False))
                result_components.append(gr.Image(label=f"第{i+1}组图片", interactive=False))
    
    # 绑定点击事件,将返回值对应到各个组件
    def update_results(query):
        texts, imgs = gradio_fn(query)
        return [texts[0], imgs[0], texts[1], imgs[1], texts[2], imgs[2], texts[3], imgs[3]]
    
    submit_btn.click(update_results, inputs=input_box, outputs=result_components)

demo.launch(share=True)

注意事项

  • 确保answer_question返回的content是长度为4的字符串列表,image_paths是长度为4的有效图片路径列表,两者顺序一一对应
  • 图片路径需是Gradio可访问的路径:本地绝对路径、DBFS路径(Databricks环境下)或网络图片URL
  • 若使用本地路径,需保证Gradio进程对该路径有读取权限

内容的提问来源于stack exchange,提问作者Danish Zahid Malik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:07:17