【问题标题】:Can I define an action on file upload when using ipywidgets FileUpload widget使用 ipywidgets FileUpload 小部件时,我可以定义文件上传操作吗
【发布时间】:2019-12-10 02:38:29
【问题描述】:

我想在使用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)

【问题讨论】:

  • 在使用小部件一段时间后,我发现(对我来说)最简单的方法是子类化小部件类并通过相关的 tartlet 监听更改。在这种情况下,这意味着创建一个类 ActionFileUpload(widgets.FileUpload) 并添加一个用 @observe(''_counter''). This new class will run whatever method appears under @observe(''_counter'') 包装的方法。

标签: python jupyter-notebook widget ipython jupyter


【解决方案1】:

你可以观察到_counter的变化

例子:

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

def on_upload_change(change):
    print(change)

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

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2015-07-17
    • 2020-05-04
    • 2015-07-09
    • 2018-01-31
    相关资源
    最近更新 更多