我正在尝试创建一个可以生成代码的小部件。创建代码后,我希望有一个按钮,当单击该按钮时,会将代码插入到新单元格中。我找到了一个名为create_code_cell的函数,但是不知道如何从javascript中运行它或如何将它嵌入到可以调用的python类中。
import ipywidgets as widgets
from traitlets import CInt
from traitlets import Unicode
import base64
from IPython.display import Javascript, display
from IPython.utils.py3compat import str_to_bytes, bytes_to_str
class CodeBuilerWidget(widgets.DOMWidget):
_view_name = Unicode('CodeBuilerView').tag(sync=True)
value = CInt().tag(sync=True)
def create_code_cell(code='', where='below'):
"""Create a code cell in the IPython Notebook.
Parameters
code: unicode
Code to fill the new code cell with.
where: unicode
Where to add the new code cell.
Possible values include:
at_bottom
above
below"""
encoded_code = bytes_to_str(base64.b64encode(str_to_bytes(code)))
display(Javascript("""
var code = IPython.notebook.insert_cell_{0}('code');
code.set_text(atob("{1}"));
""".format(where, encoded_code)))
%%javascript
require(["jupyter-js-widgets"], function(widgets) {
var CodeBuilerView = widgets.DOMWidgetView.extend({
render: function() {
var that = this;
this.$btn = $('<button id="btn">Insert Code</button>');
this.$el.append(this.$btn);
this.$btn.click(function() {
alert( "Handler for .click() called. Want to run create_code_cell() python method" );
});
},
});
widgets.ManagerBase.register_widget_view('CodeBuilerView', CodeBuilerView);
});
非常感谢