首页 > 解决方案 > 使用 ipywidgets FileUpload 小部件时,我可以定义文件上传操作吗

问题描述

我想在上传文件时创建一个事件,widgets.FileUpload就像我widgets.Button使用.on_click(some_function). 有没有办法做这样的事情

import ipywidgets as widgets

def do_something_with_file(fu):

    content = fu.data[0].decode('utf-8') 
    # doing something with the file content and get some string output
    return 'some string'

str_file_upload = widgets.FileUpload(accept='.txt', multiple=False)
str_file_upload.on_upload(do_something_with_file)

标签: pythonjupyter-notebookwidgetipythonjupyter

解决方案


可以观察 _counter 的变化

例子:

from ipywidgets import widgets
uploader = widgets.FileUpload()
display(uploader)

def on_upload_change(change):
    print(change)

uploader.observe(on_upload_change, names='_counter')

推荐阅读