【问题标题】:Enabling Multi-Select in ipython-widgets在 ipython-widgets 中启用多选
【发布时间】:2020-07-04 19:55:40
【问题描述】:

我有一个开发问题。我需要能够使用 ipython-widgets 从 python 的下拉菜单中同时选择多个项目。到目前为止,我已经能够选择一个选项单选项小部件菜单,选择后将绘制其相应的统计数据。我在下面粘贴了我的代码,如果您能帮助我,我将不胜感激。

import numpy as np
import pandas as pd
import ipywidgets as widgets
import matplotlib.pyplot as plt
import panel as pn
pn.extension()


classes= widgets.Dropdown(
description='Products:',
options= list(output_table.class_m.unique())
)


start_year = widgets.BoundedFloatText(
    value=output_table.year.min(),
    min=output_table.year.min(),
    max=output_table.year.max(),
    step=1,
    description='Start Year:',
    disabled=False,
    color='black'
)
end_year = widgets.BoundedFloatText(
    value=output_table.year.max(),
    min=output_table.year.min(),
    max=output_table.year.max(),
    step=1,
    description='End Year:',
    disabled=False,
    color='black'
)


output=widgets.Output()

def response(name, start, end):
    name = classes.value
    output.clear_output()
    df2 = output_table.copy()
   # Filter between min and max years (inclusive)
    df2 = df2[(df2.year >= start) & (df2.year <= end)]
    with output:
        if len(df2) > 0:
            plot1 = df2[df2['class_m'] == name].groupby(['month']).agg({'units':'sum'}).reset_index()
            plot1.plot(x='month', y='units')
            clear_output(wait=True)
            plt.show()
        else:
            print("No data to show for current selection")
def event_handler(change):
    response(change.new, start_year.value, end_year.value)

def start_year_handler(change):
    response(classes.value, change.new, end_year.value)

def end_year_handler(change):
    response(classes.value, start_year.value, change.new)

classes.observe(event_handler, names='value')
start_year.observe(start_year_handler, names = 'value')
end_year.observe(end_year_handler, names = 'value')

display(classes)
display(start_year)
display(end_year)

【问题讨论】:

    标签: numpy jupyter-notebook ipython ipywidgets


    【解决方案1】:

    查看 SelectMultiple 小部件 (https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20List.html#SelectMultiple)。

    w = widgets.SelectMultiple(
        options=['Apples', 'Oranges', 'Pears'],
        value=['Oranges'],
        #rows=10,
        description='Fruits',
        disabled=False
    )
    

    您可以按住shift单击选择多个选项,然后调用w.value获取所选值的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多