首页 > 解决方案 > 如何在 Python 中实现在 Azure Jupyter Notebook 中打开的文件对话框?

问题描述

我的代码:

%gui qt

from PyQt5.QtWidgets import QFileDialog

def gui_fname(dir=None):
    """Select a file via a dialog and return the file name."""
    if dir is None: dir ='./'
    fname = QFileDialog.getOpenFileName(None, "Select data file...", 
                dir, filter="All files (*);; SM Files (*.sm)")
    return fname[0]

from IPython.display import display
button = widgets.Button(description="Open The File  !!")
button.style.button_color = 'yellow'
display(button)


def on_button_clicked(b):
    print("Button clicked.")
    f=gui_fname()
    #import fileplot
    #fileplot.load_file(f)



button.on_click(on_button_clicked)
#b1 = Button(description='Open File !!')
#b1.style.button_color = 'yellow'
#b1.on_click(on_button_clicked)
#b1

问题:它在本地 pc python 版本 2.7 os Linux 中运行良好

但是当我尝试在 Azure Jupyter Notebook 中远程实现它时,每次运行代码时内核都会死掉,我无法获得结果。有没有其他方法可以在 ipython 小部件中实现带有 html5 小部件的文件对话框?

我需要什么我需要用户选择他/她的电脑中本地可用的文件。1

在此处输入图像描述

标签: pythonazurejupyter-notebookjupyter-kernelazure-notebooks

解决方案


实际上,您不能在 Azure Jupyter Notebook 上使用任何本机 GUI API,因为 Azure Jupyter Notebook 在没有任何 GUI 支持的远程 Linux 服务器上运行,并且它是用于远程访问的 Web 应用程序。

因此,如果您想为客户端用户显示文件对话框,HTML 文件对话框是您唯一的选择。简单的解决方案是使用模块的display&HTMLIPython来显示一个Choose File按钮,请看下面的代码&结果。

from IPython.display import display, HTML

display(HTML("""
    <input type="file" name="myfile">
"""))

结果是:

在此处输入图像描述

对于更复杂的案例,您可以参考这些博客IPython Notebook: Javascript/Python Bi-directional CommunicationReading files in JavaScript using the File APIs创建自己的博客。但是,缺少接收和保存上传文件的服务,需要自己实现。fileupload或者,您可以简单地为 IPython 使用名为(PyPIGitHub )的现有项目,它是“使用FileReader上传文件的 IPython 笔记本小部件”。


推荐阅读