使用HBox中的按钮删除/隐藏HBox和子窗口小部件

2024-04-25 03:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我制作的模块(see this SO question)制作一个输入小部件。你知道吗

输入小部件应该有一个标题栏和下面可变数量的输入行。我想在每个输入行的末尾都有一个删除按钮。你知道吗

理想情况下,delete按钮应该删除容器小部件和所有子部件,但是隐藏容器小部件和子部件也是可以接受的。你知道吗

我没能找到解决这个问题的有效方法。你知道吗

目前,我得到了这个代码,但我没有线索少,如何解决这个问题。你知道吗

import ipywidgets as w
​
def add_btn_clicked(b):
    input_box.children = (input_box.children[0], line()) + input_box.children[1:]
​
def delete_btn_clicked(b):
    # ???
    with output:
        print(b.keys)
    return None

add = w.Button(icon="plus-circle")
add.on_click(add_btn_clicked)
​
title = w.HBox([w.Label(value=str(i)) for i in range(3)]+[add])
​
def line():
    delete = w.Button(icon="trash")
    delete.on_click(delete_btn_clicked)
    return w.HBox([w.FloatText(value=i) for i in range(3)]+[delete])
​
input_box = w.VBox([title,line()])
output = w.Output()
​
display(input_box)
display(output)

有没有一种方法可以通过单击按钮来判断父元素是什么,或者用另一种方法来实现我正在尝试的目标?你知道吗


Tags: 方法boxaddinputoutputreturn部件def
1条回答
网友
1楼 · 发布于 2024-04-25 03:31:07

您可以分别创建小部件和容器,然后在组装到一起之前,将子部件上的.parent属性定义为容器。这样,在单击按钮时可以有效地隐藏容器(使用.parent.layout.display = 'none')。你知道吗

import ipywidgets as w

def add_btn_clicked(b):
    input_box.children = (input_box.children[0], line()) + input_box.children[1:]

def delete_btn_clicked(b):
    b.parent.layout.display = 'none'

add = w.Button(icon="plus-circle")
add.on_click(add_btn_clicked)

title = w.HBox([w.Label(value=str(i)) for i in range(3)]+[add])

def line():
    delete = w.Button(icon="trash")
    delete.on_click(delete_btn_clicked)
    val_widgets = [w.FloatText(value=i) for i in range(3)]
    container = w.HBox()
    delete.parent = container
    for widg in val_widgets:
        widg.parent = container
    children = val_widgets + [delete]
    container.children = children
    return container

input_box = w.VBox([title,line()])
output = w.Output()

display(input_box)
display(output)

相关问题 更多 >