我有一个函数createWidgets,其目的是获取字符串列表并为每个字符串创建容器列表 - > 1个容器=一个文本框和复选框。然后将每个容器放入一个大容器中。
我要做的是在容器上添加一个按钮,on_click将获取所有“True”并放入所有修改过的字符串并将它们放入数据框中
widgelist = e.options
txtBox_type = 'text_widget' # Define if Area box o regular txtbox
bigContainer = createWidgets(widgelist, txtBox_type)
Function
def createWidgets(widgelist, txtBox_type):
#containerList = []
i = 0
for k in widgelist:
## Build Container widgets
chBox_Widget = widgets.CheckboxWidget(description = str(i),value = False,)
if txtBox_type == 'textA_widget': # Check wether txtBox should be an area txt box or not.
txt_Widget = widgets.TextareaWidget( description = str(i), value = k)
else:
txt_Widget = widgets.TextWidget( description = str(i), value = k)
container = widgets.ContainerWidget()
container.children = [chBox_Widget, txt_Widget]
containerList.append(container)
i+= 1
button = widgets.ButtonWidget(description = 'Add')
bigContainer = widgets.ContainerWidget()
bigContainer.children = containerList
return bigContainer
我去了很多网站并花了很多天时间对这个帮助表示非常感谢
答案 0 :(得分:8)
尽可能地解释这个问题,下面的代码应该提供一个答案:
import IPython.html.widgets as widgets
from IPython.display import display, clear_output
import pandas as pd
df = pd.DataFrame(columns=['Thing'])
def createWidgets(widgelist):
## Each CheckboxWidget and TextWidget are enclosed in a subwidget. We use a
## list comprehension to construct a list of these subwidgets.
containerList = [
widgets.ContainerWidget(children=(widgets.CheckboxWidget(description=k)
widgets.TextWidget(value=k)))
for k in widgelist]
bigContainer = widgets.ContainerWidget(children=containerList)
## To arrange the CheckboxWidget in a row with the TextWidget, we have to
## first display them, then remove_class('vbox') and add_class('hbox'). This
## bit of awkwardness in the IPython version 2.x notebook will hopefully
## be fixed in version 3.x. Displaying bigContainer also displays it's children.
display(bigContainer)
for c in containerList:
c.remove_class('vbox')
c.add_class('hbox')
return bigContainer
widgelist = ['ThingA', 'ThingB', 'ThingC', 'ThingD']
bigContainer = createWidgets(widgelist, txtBox_type)
## Callback for button.on_click.
def add_to_dataframe(a):
# The children of bigContainer are also containers,
# each with first child a CheckboxWidget and second
# child a TextWidget. We iterate through them and
# if checked, add the text to the dataframe df as
# an additional row.
for c in bigContainer.children:
if c.children[0].value:
df.loc[len(df)+1] = (c.children[1].value,)
display(df)
clear_output()
display(df)
button = widgets.ButtonWidget(description = 'Add')
button.on_click(add_to_dataframe)
display(button)
以下是向数据框添加几行后窗口小部件区域和输出的屏幕剪辑。
我本来设计的代码有点不同,但我试着留下来 靠近您的代码组织。
答案 1 :(得分:0)
这是jupyternotebooks 4上Ipython3的更新版本
重命名:
参考:[https://ipython.org/ipython-doc/3/whatsnew/version3_widget_migration.html]