Gradio多Tab界面按钮调用异常:跨环境表现不一致求助
Gradio多Tab界面函数调用异常问题排查
问题现象
点击第二个「Farewell」标签页的Submit按钮时,实际触发的是第一个标签页的greet函数,而非预期的farewell函数;第二个标签页的输出框会一直显示处理状态,但最终结果却被填充到第一个标签页的输出框中。
复现代码
import gradio as gr # Define the function for the first tab def greet(text): return f"Hello {text}" # Define the function for the second tab def farewell(text): return f"Goodbye {text}" # Create the interface for the first tab with gr.Blocks() as greet_interface: input_text = gr.Textbox(label="Input Text") output_text = gr.Textbox(label="Output Text") button = gr.Button("Submit") button.click(greet, inputs=input_text, outputs=output_text) # Create the interface for the second tab with gr.Blocks() as farewell_interface: input_text = gr.Textbox(label="Input Text") output_text = gr.Textbox(label="Output Text") button = gr.Button("Submit") button.click(farewell, inputs=input_text, outputs=output_text) # Combine the interfaces into tabs with gr.Blocks() as demo: with gr.Tabs(): with gr.TabItem("Greet"): greet_interface.render() with gr.TabItem("Farewell"): farewell_interface.render() # Launch the interface # demo.launch() demo.launch(server_name="0.0.0.0", server_port=7861)
环境差异
正常运行环境
- Python 3.11.1
- 使用venv
- Gradio 4.37.2
异常环境
- Python 3.9.16
- 使用Poetry
- Gradio 4.32.2
结论与解决方案
这个问题是Gradio 4.32.2版本中存在的Tab嵌套Blocks组件时的事件绑定bug,在后续的4.37.2版本中已经被修复。原因是早期版本中,独立Blocks实例在Tab内渲染时,组件的唯一标识没有被正确隔离,导致不同Tab的事件绑定出现混淆。
解决方法
- 升级Gradio版本(推荐):在异常环境中把Gradio升级到4.37.2或更高版本,使用Poetry执行命令:
poetry add gradio@>=4.37.2
- 调整代码实现(无法升级时):避免创建独立的Blocks实例,直接在
TabItem内部构建界面组件,示例代码如下:
import gradio as gr def greet(text): return f"Hello {text}" def farewell(text): return f"Goodbye {text}" with gr.Blocks() as demo: with gr.Tabs(): with gr.TabItem("Greet"): input_text_greet = gr.Textbox(label="Input Text") output_text_greet = gr.Textbox(label="Output Text") button_greet = gr.Button("Submit") button_greet.click(greet, inputs=input_text_greet, outputs=output_text_greet) with gr.TabItem("Farewell"): input_text_farewell = gr.Textbox(label="Input Text") output_text_farewell = gr.Textbox(label="Output Text") button_farewell = gr.Button("Submit") button_farewell.click(farewell, inputs=input_text_farewell, outputs=output_text_farewell) demo.launch(server_name="0.0.0.0", server_port=7861)
内容的提问来源于stack exchange,提问作者KansaiRobot
相关产品推荐
相关产品推荐

