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



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

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

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"时将其替换为正确的术语。 最终,这将适用于过滤大熊猫网格。 我尝试使用 Ipython.display 并将函数组装到要清除的输出中,但是,根据我所做的,它要么清除所有内容,要么什么都不清除。

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

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

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

尝试使用单独的输出小部件 (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')

我在这篇文章的帮助下解决了它: 从笔记本中清除 Jupyter 笔记本中单元格的小组件区域

看来显示和输出函数必须存在于我定义的函数之外。 话虽如此,我仍然停留在一块 - 如果有人可以解释如何在从按钮调用时将多个变量传递到此函数中,将不胜感激,因为一旦我重新引入多个变量,我会收到有关参数位置的错误。

最新更新