Ipywidgets 与 Google Colaboratory

Ipywidgets with Google Colaboratory

我正在尝试将 ipywidgets 与 Google Colaboratory 一起使用,并且(与 ) the simplest example from the docs 一样不起作用。下面的代码在本地笔记本中显示了一个滑块,但只有 returns 10 <function __main__.f> 在 Google 笔记本中。

!pip install ipywidgets

from ipywidgets import interact

def f(x):
  return x

interact(f, x=10)

我可以使用另一个自定义初始化来启用小部件吗?

更新 2:核心 ipywidgets 现在可以在 Colab 中使用,许多自定义小部件也是如此!特别是,基础、控件、FileUpload、Image 和输出小部件都在 colab 中工作。有关详细信息,请参阅 https://github.com/googlecolab/colabtools/issues/498

(调整后的原始答案):ipywidgets 不要只使用 Colab:我们有不同的安全模型,其中每个输出都在自己的 iframe 中(与 Colab 主页面的来源不同) .这会阻止 ipywidgets 在 Colab 端没有更改的情况下工作。

我想现在 Ipywidgets 正在与 Google Collaboratory 合作。我测试了一些装饰器,它 运行 很顺利。

您的代码导致:

ipywidgets 现在 kinda-supported 在 colab 中;一个值得注意的例外是 ipywidgets.Image。参见 https://github.com/googlecolab/colabtools/issues/587

!pip install ipywidgets

# this will allow the notebook to reload/refresh automatically within the runtime
%reload_ext autoreload
%autoreload 2

from ipywidgets import interact

def f(x):
  return x

interact(f, x=10)

截至 2021-12 年,ipywidgets(小部件)在 Colab 中完美运行。嗯,也许不是 100%,但数量相当可观。

您只需要导入它们(以您喜欢的任何方式,下面有 2 个示例)

import ipywidgets as widgets
from ipywidgets import interact, interactive, fixed

并使用(简单示例)

widgets.Select(
    options=['Linux', 'Windows', 'macOS'],
    value='macOS',
    # rows=10,
    description='OS:',
    disabled=False
)

你这里有很棒的文档https://ipywidgets.readthedocs.io