Python 如何用“替换对象”;curdoc().clear();使用模板?还有可能吗?

Python 如何用“替换对象”;curdoc().clear();使用模板?还有可能吗?,python,python-3.x,jinja2,bokeh,Python,Python 3.x,Jinja2,Bokeh,我正在尝试替换一些根对象。插入替换法效果良好 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 impor

我正在尝试替换一些根对象。插入替换法效果良好

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)
使用方法
覆盖\u plot
将对象添加到底部,而不是模板位置:

模板:

{% extends base %}

{% block contents %}

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

        </div>
    </div>

{% endblock %}

他们是,你在这里看到的,是一个完全有效的行为。问题在于,新创建的根模型的ID与bokeh在初始嵌入时知道的ID不同。要解决此问题,可以使用与原始模型相同的id创建新根(因此
col=column(id=c.\u id,…)
)。这样,bokeh将把新根嵌入模板中的原始槽中。但是,修改根应该是最后一种使用方法。更可取的做法是修改现有模型或布局(如在
覆盖\u plot2
中所做的)

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