如何创建一个 Jupyter Lab 扩展,在 Jupyter Lab 笔记本的工具栏上添加一个自定义按钮?

Cal*_*Oki 7 dom typescript jupyter-notebook jupyter-lab

我正在尝试创建一个扩展程序,在打开的 Jupyter Lab 笔记本的工具栏中添加一个自定义按钮,类似于这张照片中的“提交笔记本按钮......”。我如何实现这一目标?我尝试使用以下代码但它不起作用:

import { ToolbarButton } from "@jupyterlab/apputils";
import { DocumentRegistry } from "@jupyterlab/docregistry";
import { INotebookModel, NotebookPanel } from "@jupyterlab/notebook";
import { IDisposable } from "@lumino/disposable";

export class ButtonExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {

  createNew(panel: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
    // Create the toolbar button
    let mybutton = new ToolbarButton({
        label: 'My Button',
        onClick: () => alert('You did it!')
    });

    // Add the toolbar button to the notebook toolbar
    panel.toolbar.insertItem(10, 'mybutton', mybutton);

    // The ToolbarButton class implements `IDisposable`, so the
    // button *is* the extension for the purposes of this method.
    return mybutton;
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

kra*_*ski 2

您的按钮代码看起来不错,但不包含为笔记本注册按钮的实际应用程序插件:

import {
  JupyterFrontEnd,
  JupyterFrontEndPlugin
} from '@jupyterlab/application';

const yourPlugin: JupyterFrontEndPlugin<void> = {
  id: '@your-org/plugin-name',
  autoStart: true,
  activate: (app: JupyterFrontEnd) => {
    const your_button = new ButtonExtension();
    app.docRegistry.addWidgetExtension('Notebook', your_button);
  }
}

export default yourPlugin;
Run Code Online (Sandbox Code Playgroud)

您可能想通过查看这些向笔记本添加按钮的扩展的代码来学习:

另外,如果您的目的是附加按钮,则可以替换insertItem()为。addItem()如果这是您的第一个扩展,我强烈建议您遵循本教程并在此基础上进行构建。