python - 如何使用模板将对象替换为“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()
解决方案
它们和您在这里看到的一样,是一种完全有效的行为。问题是新创建的根模型与散景从初始嵌入中知道的不同 id。要解决此问题,您可以创建具有与原始模型相同的 id 的新根 (so col = column(id=c._id, ...)
)。这样,散景会将新根嵌入模板的原始插槽中。但是,修改根应该是最后使用的方法。修改现有模型或布局更为可取(就像您在 中所做的那样overrides_plot2
)。
推荐阅读
- javascript - 在 Vue.js 中导入引导程序
- php - 如何将 Laravel Http 响应作为 json 对象而不是数组返回?
- python - 使用多个元素从 HTML 中抓取数据
- web-scraping - scrapy 返回 response.status 505
- java - iText为复选框设置边框颜色和宽度,但它不起作用
- c - 如何与 C 标准输出通信?
- reactjs - react-query:useQuery 返回 undefined 并且组件不会重新渲染
- node.js - 对 React 应用程序中的每个组件进行单元测试真的很重要吗?
- android - 在 Flutter 或 React Native 上具有完整功能的 Native Camera?
- c++ - 什么特征使得 uninitialized_copy(_n) 可以被 copy(_n) 所取代?