我想知道每当您操作/改变/滑动/更改其他交互式参数之一时,ipywidgets 是否支持将其中一个参数重置为默认值。以 documentation 中的一个基本示例为例
%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
def f(m, b):
plt.figure(2)
x = np.linspace(-10, 10, num=1000)
plt.plot(x, m * x + b)
plt.ylim(-5, 5)
plt.show()
interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot
我想要的是一种每当我更改 m 时将参数 b 重置为某个默认值的方法。这是否受支持,如果不支持,是否有人能够想出一种聪明的方法来做到这一点?我个人做不到。
最佳答案
这是一个相当简化的示例,但您可以将 default_value
定义为 b
的普通实例变量,然后每当 m
时重新分配它> 通过普通的observe
命令进行更改。
在这种情况下,如果您有两个或多个交互的小部件,则作为一个 类
进行管理可能会更容易,其中两个输入是实例变量,特别是如果您想在同一模块/笔记本中的多个位置。
%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
def f(m, b):
plt.figure(2)
x = np.linspace(-10, 10, num=1000)
plt.plot(x, m * x + b)
plt.ylim(-5, 5)
plt.show()
interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
m = interactive_plot.children[0]
b = interactive_plot.children[1]
b.default_value = 0
def set_b_default(button):
b.value = b.default_value
m.observe(set_default)
interactive_plot
关于python - 使用交互改变另一个参数时重置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53379680/