Jupyter Notebook不随ipywidget更改而更新

时间:2020-04-17 15:11:42

标签: python ipywidgets

当我更新窗口小部件时,什么也没有发生。 我正在尝试显示条形图并根据小部件输入选择数据。 我有一个600行的小型数据框。每行都有M atk_dice,N def_dice和atk_tl bool,以及其他一些选择器。数据是一个可变长度列表,它将是概率分布函数的条形图。

import plotly.graph_objects as go 
import pandas as pd
import numpy as np
from ipywidgets import widgets

atk_dice = widgets.IntSlider(
    value = 1.0,
    min = 1.0,
    max = 6.0,
    step = 1.0,
    description = 'Number of Attack Dice',
    continuous_update = False)

def_dice = widgets.IntSlider(
    value = 1.0,
    min = 1.0,
    max = 6.0,
    step = 1.0,
    description = 'Number of Defense Dice',
    continuous_update = False)

tgt_lk = widgets.Checkbox(
    description = 'Target Lock',
    value = False)

container = widgets.HBox(children = [atk_dice, def_dice, tgt_lk])

j = 1
row = df.iloc[j]
M = (row['M_atk_dice'])
mPhr = row.Phr
mhits = np.arange(M+1)
trace1 = go.Bar(x = mhits, y = mPhr, opacity= 0.8, name = 'pdf')
g = go.FigureWidget(data = [trace1], 
                    layout = go.Layout(
                        title = dict(text = 'PDF')
                    )
                   )


def response(change):
    M = 10
    x1 = np.arange(M+1)
    y1 = x1

    with g.batch_update():
        g.data[0].x = x1
        g.data[0].y = y1

atk_dice.observe(response, names = "All", type = "change")
def_dice.observe(response, names = "All", type = "change")
tgt_lk.observe(response, names = "All", type = "change")        

widgets.VBox([container, g])

谢谢。

1 个答案:

答案 0 :(得分:0)

在建立这些功能并进行交互时,我总是尝试从基本的print功能开始。在name='All'调用中使用observe是不正确的,所有dict键都不匹配name=All,因此不会运行您的函数。查看在滑块中观察到的nametype,它们在观察调用中没有任何扭曲:

import pandas as pd
import numpy as np
from ipywidgets import widgets

atk_dice = widgets.IntSlider(
    value = 1.0,
    min = 1.0,
    max = 6.0,
    step = 1.0,
    description = 'Number of Attack Dice',
    continuous_update = False)

def response(change):
    print(change)

atk_dice.observe(response)
atk_dice
{'name': '_property_lock', 'old': traitlets.Undefined, 'new': {'value': 2}, 'owner': IntSlider(value=1, continuous_update=False, description='Number of Attack Dice', max=6, min=1), 'type': 'change'}
{'name': 'value', 'old': 1, 'new': 2, 'owner': IntSlider(value=2, continuous_update=False, description='Number of Attack Dice', max=6, min=1), 'type': 'change'}
{'name': '_property_lock', 'old': {'value': 2}, 'new': {}, 'owner': IntSlider(value=2, continuous_update=False, description='Number of Attack Dice', max=6, min=1), 'type': 'change'}

您可能想要atk_dice.observe(response, names = "value", type = "change")