首页 > 解决方案 > 如何使用模板将对象替换为“curdoc().clear()”?还有可能吗?

问题描述

我正在尝试替换一些根对象。插入替换的方法工作正常。

from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models.widgets.buttons import Button
from bokeh.models import Plot, Column
from bokeh.plotting.figure import Figure
from bokeh.layouts import column
import numpy as np

N = 2
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
p = figure(name='fig', width=300, height=200)
p.scatter(x, y, size=10, fill_color='red',)

def overrides_plot():
    print('Overriding with new plot')
    N = 2
    x = np.random.random(size=N) * 100
    y = np.random.random(size=N) * 100
    p2 = figure(name='fig2', width=300, height=200)
    p2.scatter(x, y, size=10, fill_color='blue',)

    curdoc().clear()
    col = column(children=[p2, ov, ov2], name='main_column')
    curdoc().add_root(col)      # this adds the objects at the bottom, instead of the template place

ov = Button(
    name='override',
    label='Override',
    button_type='success',
    width=50
)
ov.on_click(overrides_plot)

def overrides_plot2():
    print('Overriding with new plot with remove/insert')
    N = 2
    x = np.random.random(size=N) * 100
    y = np.random.random(size=N) * 100
    p3 = figure(name='fig3', width=300, height=200)
    p3.scatter(x, y, size=10, fill_color='black',)

    p = curdoc().select_one(selector=dict(type=Figure))
    c = curdoc().select_one(selector=dict(type=Column))
    c.children.remove(p)
    c.children.insert(0, p3)

ov2 = Button(
    name='override',
    label='Overrides with remove/insert',
    button_type='success',
    width=50
)
ov2.on_click(overrides_plot2)
c = column(children=[p, ov, ov2], name='main_column')
curdoc().add_root(c)

使用该方法overrides_plot将对象添加到底部而不是模板位置:

模板:

{% extends base %}

{% block contents %}

    <div class="container body">
        <div class="main_container">
            <div>
                {{ embed(roots.main_column) }}
            </div>

        </div>
    </div>

{% endblock %}

那么这些方法还有用吗?

curdoc().clear()
curdoc().remove_root()

标签: pythonpython-3.xjinja2bokeh

解决方案


它们和您在这里看到的一样,是一种完全有效的行为。问题是新创建的根模型与散景从初始嵌入中知道的不同 id。要解决此问题,您可以创建具有与原始模型相同的 id 的新根 (so col = column(id=c._id, ...))。这样,散景会将新根嵌入模板的原始插槽中。但是,修改根应该是最后使用的方法。修改现有模型或布局更为可取(就像您在 中所做的那样overrides_plot2)。


推荐阅读