1

下面的代码是散景模型在通过回调设置属性时不更新的问题的最小示例。我发现从 curdoc 的布局中删除和添加模型对象(甚至不是可疑对象)会强制它刷新。我已经通过第一次按下按钮展示了这一点。

有没有更优雅的方法来强制散景重绘图形?

该示例适用于 DataTable.columns.formatter,但我注意到这也适用于其他模型属性(包括轴范围,我已经看到了一种解决方法,涉及在图形创建时明确设置范围以允许更新)。

from bokeh.models.widgets import Dropdown, RadioButtonGroup, CheckboxGroup, \
    Toggle, DataTable, TableColumn, NumberFormatter
from bokeh.plotting import figure, curdoc, ColumnDataSource
from bokeh.layouts import column, layout


def update_format(attr, old, new):
    if toggle_commas.active == 1:
        (t.columns[1].formatter)
        # remove the commas
        t.columns[1].formatter = NumberFormatter(format='0,0.[00]')
        # show that it updates the actual attribute
        print(t.columns[1].formatter)
        del doc_layout.children[-1]
        doc_layout.children.insert(1, toggle_commas)
    else:
        # change the formatter back and note that it doesn't update the table unless you remove and add something
        (t.columns[1].formatter)
        # remove the commas
        t.columns[1].formatter = NumberFormatter(format='0.[00]')
        # show that it updates the actual attribute
        print(t.columns[1].formatter)

table_data = dict(
        percentiles=['min', '1st', '5th', '10th', '25th', '50th',
                     '75th', '90th', '95th', '99th', 'max', '', 'mean', 'std'],
        values=[i for i in range(1000, 1014)]
    )
table_source = ColumnDataSource(table_data)
table_columns = [
    TableColumn(field="percentiles", title="Percentile"),
    TableColumn(field="values", title="Value", formatter=NumberFormatter(format='0.[00]'))
    ]

t = DataTable(source=table_source, columns=table_columns, width=400, height=600,
              name='pct_table')

toggle_commas = Toggle(label='Commas', active=False)
toggle_commas.on_change('active', update_format)

doc_layout = layout(t, toggle_commas)
curdoc().add_root(doc_layout)
4

0 回答 0