最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to make choices of magicgui's `ComboBox` dependent on current value of other `ComboBox`? - Stack Overflow

programmeradmin3浏览0评论

I want to create a magicgui widget that contains two ComboBox widgets. The choices of the second ComboBox should depend on the current value of the first ComboBox. How can I accomplish that?

I know that the choices keyword of the @magicgui decorator can use functions as input.

I want to create a magicgui widget that contains two ComboBox widgets. The choices of the second ComboBox should depend on the current value of the first ComboBox. How can I accomplish that?

I know that the choices keyword of the @magicgui decorator can use functions as input.

Share Improve this question asked Mar 19 at 11:53 Niklas NetterNiklas Netter 5710 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

The following code should illustrate how to achieve two ComboBox widgets where the choices of the second depend on the current value of the first. This makes use of the changed signal of the first ComboBox to call the reset_choices of the second ComboBox to update its choices whenever the value of the first ComboBox got changed. The possible choices are saved as a dict.

# Dictionary to save choice dependencies.
choices = {
    "Choice 1": ["First A", "First B", "First C"],
    "Choice 2": ["Second A", "Second B", "Second C", "Second D"],
    "Choice 3": ["Only one choice"],
}

# The choices function receives the `ComboBox`
# widget as argument.
def get_second_choice(gui):
    # before final initialization the parent
    # of our `ComboBox` widget is None.
    if gui.parent is not None:
        return choices[gui.parent.box1.value]
    else:
        return []

@magicgui(
    box1={"widget_type": "ComboBox", "choices": list(choices.keys())},
    box2={"widget_type": "ComboBox", "choices": get_second_choice},
)
def widget(box1, box2, viewer: napari.Viewer) -> None:
    return f"{box1} - {box2}"

# Changes to box1 should result in resetting
# choices in box2.
widget.box1.changed.connect(widget.box2.reset_choices)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论