【问题标题】:gradio refresh interface when selecting File选择File时gradio刷新界面
【发布时间】:2023-02-08 19:04:18
【问题描述】:

我正在尝试创建一个执行以下操作的 gradio 用户界面

  1. 在左侧面板上我有一个文件控件,它允许选择本地文件(例如 .csv)
  2. when a file is selected a "Process" button should be made visible
  3. 当按下“Process”按钮时,一个函数被调用,读取文件的内容,并以某种方式处理它,产生一个字符串
  4. 结果字符串显示在右列的 TextArea 中

    我坚持执行第 2 点。我可以选择文件,但无法使“处理”按钮可见。

    到目前为止,这是我的代码(尚未实施第 3.a 点:

    import gradio as gr
    
    def file_selected(file_input):
        print("yes, file_selected is invoked")
        print(process_button)
        process_button.visible=True
        demo.render()
        return process_button
    
    with gr.Blocks() as demo:
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### Data")
                file_input = gr.File(label="Select File")
                process_button = gr.Button("Process", visible=False)
    
            with gr.Column(scale=2, min_width=600):
                gr.Markdown("### Output")
                result_display = gr.TextArea(default="", label="Result", lines=10, visible=False)
    
        file_input.change(fn=file_selected, inputs=file_input, outputs=process_button)
        
    if __name__ == "__main__":
        demo.launch()    
    

    我看到在选择文件时打印了消息(print(process_button) 打印了"button" 所以我确定这个变量不是 None),但是按钮没有出现在页面上。

    编辑:修复了一些与问题没有直接关系的错误。

【问题讨论】:

    标签: python gradio


    【解决方案1】:

    代码有很多问题(我修复了那些与原始帖子中的主要问题无关的问题),但最终解决了我的问题(使按钮可见)是重新渲染,

    def file_selected():
        ...
        process_button.visible=True
        demo.render()
    

    我只需要返回 process_button.update

    def file_selected(file_input):
        ...
        return gr.update(visible=True)
    

    (实际上这在gradio的在线文档中有记录;抱歉,我之前没有注意到)

    这是完整的工作代码:

    import gradio as gr
    
    def file_selected(file_input):
        print("yes, file_selected is invoked")
        print(process_button)
        return gr.update(visible=True)
        
    with gr.Blocks() as demo:
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### Data")
                file_input = gr.File(label="Select File")
                process_button = gr.Button("Process", visible=False)
    
            with gr.Column(scale=2, min_width=600):
                gr.Markdown("### Output")
                result_display = gr.TextArea(default="", label="Result", lines=10, visible=False)
    
        file_input.change(fn=file_selected, inputs=file_input, outputs=process_button)
        
    if __name__ == "__main__":
        demo.launch()    
    

    【讨论】:

      猜你喜欢
      • 2012-06-07
      • 2017-12-14
      • 2016-05-16
      • 2016-03-31
      • 1970-01-01
      • 2012-09-05
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多