Python 函数运行后部分刷新或清除 Jupyter 单元格显示

Partial refresh or clear of Jupyter cell display after Python function runs

我正在通过 Anaconda 使用 Python 3.7.1 和 Jupyter Notebook 6.0.1。

我正在尝试 运行 Python 中的一些基本分析,使用由 ipywidget 下拉列表初始化的函数来过滤数据。如果下拉列表中的值发生变化,我希望的状态是让下拉列表保留在屏幕上,但刷新函数过滤的任何数据。我构建了以下示例以尝试进一步测试:

import ipywidgets as widgets
from IPython.display import clear_output
def mytest(x):
    outs = widgets.Output()
    outs.clear_output()
    with outs:
        lookhere = mytestfilter.value
        if lookhere==1:
            print("hello")
        if lookhere==0:
            print("goodbye")
    display(outs)

mytestfilter = widgets.Dropdown(options={'night': 0, 'morning': 1}, description="FILTER")
display(mytestfilter)
outs=mytestfilter.observe(mytest, names='value')

基本上,在此示例中,所需的状态是擦除 "hello" 或 "goodbye" 并在 "FILTER" 更改时将其替换为正确的术语。最终,这将适用于过滤 pandas 网格。我已经尝试使用 Ipython.display 并将函数组装到要清除的输出,但是,根据我所做的,它要么清除所有内容,要么什么都不清除。

我尝试过的事情: -我试图将 clear_output 移动到函数的开头以清除现有的任何内容。由于第一个 运行 "outs" 变量不存在,我还尝试将它放在 if 语句和 try/except 中。它似乎没有做任何事情。 -我尝试了不同的分配变量、显示变量和清除输出的不同顺序,但没有成功。

我怀疑问题可能部分出在函数 运行ning 的方式上,并且变量存在于函数内部。似乎它启动了一个新的输出,一旦函数被转义,输出将保留在笔记本中,无论我下次尝试清除函数 运行s.

我在尝试设置测试时参考了以下示例: https://github.com/jupyter-widgets/ipywidgets/issues/1744

我能够在这个 post 的帮助下解决它: Clear widget area of a cell in a Jupyter notebook from within notebook

看来显示和输出函数必须存在于我定义的函数之外。话虽这么说,我仍然停留在一件事情上——如果有人能解释如何在从按钮调用时将多个变量传递给这个函数,那将不胜感激,因为一旦我引入多个变量,我就会收到有关位置的错误参数。

尝试使用单独的输出小部件 (outs = widgets.Output()),它是在您的交互功能之外创建的。

import ipywidgets as widgets
from IPython.display import clear_output
outs = widgets.Output()

def mytest(x):
    with outs:
        clear_output()
        lookhere = mytestfilter.value
        if lookhere==1:
            print("hello")
        if lookhere==0:
            print("goodbye")

mytestfilter = widgets.Dropdown(options={'night': 0, 'morning': 1}, description="FILTER")
display(mytestfilter)
display(outs)
mytestfilter.observe(mytest, names='value')