使用 ipywidgets FileUpload 小部件时,我可以定义文件上传操作吗

Can I define an action on file upload when using ipywidgets FileUpload widget

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

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)

可以观察_counter的变化

示例:

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

def on_upload_change(change):
    print(change)

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