首页 > 解决方案 > python终端不支持ipywidgets

问题描述

我正在尝试使用 python 终端运行以下代码,当我在 jupyter notebook 中运行时它工作得很好,但在 ubuntu 终端中它会抛出错误。甚至尝试跑步

jupyter nbextension enable --py --sys-prefix widgetsnbextension
在终端上我仍然收到同样的错误

import matplotlib as mp
from pylab import *
from sklearn import datasets
from ipywidgets import interact, widgets
from IPython.display import display, clear_output

faces = datasets.fetch_olivetti_faces()

class Trainer:
    def __init__(self):
        self.results = {}
        self.imgs = faces.images
        self.index = 0

    def increment_face(self):
        if self.index + 1 >= len(self.imgs):
            return self.index
        else:
            while str(self.index) in self.results:
                print(self.index)
                self.index += 1
            return self.index

    def record_result(self, smile=True):
        self.results[str(self.index)] = smile

trainer = Trainer()

button_smile = widgets.Button(description='smile')
button_no_smile = widgets.Button(description='sad face')

def display_face(face):
    clear_output()
    imshow(face, cmap='gray')
    axis('off')
    show()

def update_smile(b):
    trainer.record_result(smile=True)
    trainer.increment_face()
    display_face(trainer.imgs[trainer.index])

def update_no_smile(b):
    trainer.record_result(smile=False)
    trainer.increment_face()
    display_face(trainer.imgs[trainer.index])

button_no_smile.on_click(update_no_smile)
button_smile.on_click(update_smile)

display(button_smile)
display(button_no_smile)
display_face(trainer.imgs[trainer.index])

当我从 python 终端运行时出现回溯错误

Widget Javascript not detected.  It may not be installed properly. Did you enable the widgetsnbextension? If not, then run "jupyter nbextension enable --py --sys-prefix widgetsnbextension"
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/IPython/core/formatters.py in __call__(self, obj)
    880             method = get_real_method(obj, self.print_method)
    881             if method is not None:
--> 882                 method()
    883                 return True
    884 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipywidgets/widgets/widget.py in _ipython_display_(self, **kwargs)
    480                 loud_error('The installed widget Javascript is the wrong version.')
    481 
--> 482             self._send({"method": "display"})
    483             self._handle_displayed(**kwargs)
    484 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipywidgets/widgets/widget.py in _send(self, msg, buffers)
    485     def _send(self, msg, buffers=None):
    486         """Sends a message to the model in the front-end."""
--> 487         self.comm.send(data=msg, buffers=buffers)
    488 
    489 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipykernel/comm/comm.py in send(self, data, metadata, buffers)
    119         """Send a message to the frontend-side version of this comm"""
    120         self._publish_msg('comm_msg',
--> 121             data=data, metadata=metadata, buffers=buffers,
    122         )
    123 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipykernel/comm/comm.py in _publish_msg(self, msg_type, data, metadata, buffers, **keys)
     64         metadata = {} if metadata is None else metadata
     65         content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
---> 66         self.kernel.session.send(self.kernel.iopub_socket, msg_type,
     67             content,
     68             metadata=json_clean(metadata),

AttributeError: 'NoneType' object has no attribute 'session'
<ipywidgets.widgets.widget_button.Button at 0x7f0de5ebfb38>
Widget Javascript not detected.  It may not be installed properly. Did you enable the widgetsnbextension? If not, then run "jupyter nbextension enable --py --sys-prefix widgetsnbextension"
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/IPython/core/formatters.py in __call__(self, obj)
    880             method = get_real_method(obj, self.print_method)
    881             if method is not None:
--> 882                 method()
    883                 return True
    884 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipywidgets/widgets/widget.py in _ipython_display_(self, **kwargs)
    480                 loud_error('The installed widget Javascript is the wrong version.')
    481 
--> 482             self._send({"method": "display"})
    483             self._handle_displayed(**kwargs)
    484 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipywidgets/widgets/widget.py in _send(self, msg, buffers)
    485     def _send(self, msg, buffers=None):
    486         """Sends a message to the model in the front-end."""
--> 487         self.comm.send(data=msg, buffers=buffers)
    488 
    489 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipykernel/comm/comm.py in send(self, data, metadata, buffers)
    119         """Send a message to the frontend-side version of this comm"""
    120         self._publish_msg('comm_msg',
--> 121             data=data, metadata=metadata, buffers=buffers,
    122         )
    123 

/home/harish/anaconda3/envs/facial_env/lib/python3.4/site-packages/ipykernel/comm/comm.py in _publish_msg(self, msg_type, data, metadata, buffers, **keys)
     64         metadata = {} if metadata is None else metadata
     65         content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
---> 66         self.kernel.session.send(self.kernel.iopub_socket, msg_type,
     67             content,
     68             metadata=json_clean(metadata),

AttributeError: 'NoneType' object has no attribute 'session'
<ipywidgets.widgets.widget_button.Button at 0x7f0ddadc2cc0>

标签: python-3.xipythonjupyter-notebookipywidgets

解决方案


来自用户 6764549 的评论:

Ubuntu 终端不支持交互式小部件。您需要在可以运行 Javascript 的类似“浏览器”或启用 GUI 的环境中运行它。

Jupyter notebook 不是问题,Ubuntu 终端是问题。它不支持显示图像或小部件。如果您只是想避免使用浏览器,您可以查看Jupyter Qt 控制台Spyder


推荐阅读