如何将两个按钮的值链接到彼此相反的值? widgets.jslink() 函数似乎只链接相同的值,而不是相反的值。我知道我可以使用 widgets.ToggleButtons() 链接两个按钮,但我希望成功按钮为绿色,失败按钮为红色。 ToggleButtons() 似乎不允许每个按钮使用不同的颜色。如果确实如此,我也愿意将其作为解决方案。这是我到目前为止的代码(仅供参考:我使用 ipywidgets 和 node.js 在 JupyterLab 中运行此代码):
button_y= widgets.Button(
description='Success',
disabled=False,
button_style='success'
tooltip='Click me',
icon='check'
)
button_n= widgets.Button(
description='Failure',
disabled=False,
button_style='danger'
tooltip='Click me',
icon='check'
)
display(widgets.HBox((button_y, button_n)))
输出:
猜测您想要链接
disabled
属性。
您可以在后端使用observe
方法为链接添加逻辑:
def toggle_button_n(value):
button_n.disabled = not value.new
def toggle_button_y(value):
button_y.disabled = not value.new
button_n.observe(toggle_button_y, names=['disabled'])
button_y.observe(toggle_button_n, names=['disabled'])
您还需要更改初始化,以便仅启用其中一个按钮。
所以这个方法有点复杂,但是...正如您在OP中提到的,要使用jslink同步小部件值的逆而不依赖于Python内核,那么这个解决方案使用ipyvuetify来实现这一点模板。
import traitlets
import ipyvuetify as v
import ipywidgets as widgets
class InvertCheckbox(v.VuetifyTemplate):
"""
A class that creates a checkbox with an inverse value.
Used with inverted_jslink - A function that links two widgets with an inverse relationship. See function below
"""
val = traitlets.Bool(True).tag(sync=True)
invert_val = traitlets.Bool(False).tag(sync=True)
template = traitlets.Unicode('''
<template>
<div>
<v-checkbox v-model="val" />
</div>
</template>
<script>
export default {
watch: {
val: function(newVal, oldVal) {
if (newVal !== oldVal) {
this.invert_val = !newVal;
}
},
invert_val: function(newVal, oldVal) {
if (newVal !== oldVal) {
this.val = !newVal;
}
}
}
}
</script>
''').tag(sync=True)
def inverted_jslink(widget1,widget2,not_widget):
"""
A function that links two widgets with an inverse relationship."""
widgets.jslink(widget1, (not_widget, "val"))
widgets.jslink((not_widget, "invert_val"), widget2)
button_y= widgets.Button(
description='Success',
disabled=True,
button_style='success',
tooltip='Click me',
icon='check'
)
button_n= widgets.Button(
description='Failure',
disabled=False,
button_style='danger',
tooltip='Click me',
icon='check'
)
not_widget = InvertCheckbox()
inverted_jslink(
(button_y, "disabled"), (button_n, "disabled")
,not_widget)
display(widgets.HBox((button_y, button_n)))
不要在 Jupyter 中尝试这些命令...
button_n.disabled = True
button_n.disabled = False
button_y.disabled
button_y.disabled = True