在Jupyter笔记本中,我想让三个滑块的总和保持不变,其中一个滑块的值更改会通过生成随机数来触发其他两个滑块的更改。我当前的方法是s:
import ipywidgets as widgets
import numpy as np
from IPython.display import display
y = widgets.FloatSlider(min=0, max=100, step=1, description="Yes")
n = widgets.FloatSlider(min=0, max=100, step=1, description="No")
a = widgets.FloatSlider(min=0, max=100, step=1, description="Abstention")
output = widgets.Output()
@output.capture()
def slider_y_eventhandler(change):
output.clear_output()
n.value = np.random.randint(0, 100 - change["new"])
a.value = 100 - sum([change["new"], n.value])
with output:
if sum([n.value, change["new"]]) >= 100:
logger.debug()
print(sum((y.value, n.value, a.value)))
@output.capture()
def slider_n_eventhandler(change):
output.clear_output()
y.value = np.random.randint(0, 100 - change["new"])
a.value = 100 - sum([change["new"], n.value])
with output:
logger.debug(change["owner"])
print(sum((y.value, n.value, a.value)))
@output.capture()
def slider_a_eventhandler(change):
output.clear_output()
y.value = np.random.randint(0, 100 - change["new"])
n.value = 100 - sum([change["new"], a.value])
with output:
logger.debug(change["owner"])
print(sum((y.value, n.value, a.value)))
y.observe(slider_y_eventhandler, names="value")
n.observe(slider_n_eventhandler, names="value")
a.observe(slider_a_eventhandler, names="value")
display(y, n, a, output)
问题在于,通过更改滑块a
的值,内核会不断从其他两个滑块的更改中撤消直到崩溃。有什么办法可以防止这种情况?还是我以错误的方式来解决问题?