python - 如何让 Bokeh 按钮调用一个函数(使用 CustomJS)
问题描述
我可以使用 curdoc 选项获得功能,然后使用“bokeh serve bokehcode.py”,然后让我的烧瓶代码(称为 app.py)参考这个散景图。但是我需要一个包含散景部分的python代码,并且我遇到了一个问题,即单击按钮来调用更新我的绘图/图形的函数。我一整天都没有运气。
为了简单起见,我删除了所有功能(甚至是 Flask 部分)并在下面放置了一个简化的代码,我需要在没有 curdoc选项的情况下工作(所以主要是使用 customjs 回调?)。然后我可以将它扩展到我的功能。
from bokeh.models.widgets import TextInput,Button,Paragraph
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.plotting import figure
inptxt = TextInput()
displaytxt = Paragraph()
button = Button()
p = figure(plot_width=400, plot_height=400)
def myfunc():
displaytxt.text=inptxt.value
p.xaxis.axis_label = inptxt.value
button.on_click(myfunc)
layout=column(inptxt,displaytxt,button,p)
curdoc().add_root(layout)
在我的实际代码中,'myfunc()' 会做很多事情,包括一些机器学习的东西,然后它会更新绘图。我希望在单击按钮时调用此 myfunc 并更新图形(p),并且我希望在不使用 curdoc 的情况下实现它。非常感谢有关如何执行此操作的任何帮助。
解决方案
from bokeh.layouts import column
from bokeh.models import CustomJS, TextInput, Button, Paragraph
from bokeh.plotting import figure, show
inptxt = TextInput()
displaytxt = Paragraph()
button = Button()
p = figure(plot_width=400, plot_height=400,
# Note that without setting the initial label,
# setting it with the button will not make it
# visible unless you interact with the plot, e.g.
# by panning it. I've created
# https://github.com/bokeh/bokeh/issues/10362
# for this.
x_axis_label='hello')
p.circle(0, 0) # To avoid having a blank plot.
def myfunc():
displaytxt.text = inptxt.value
p.xaxis.axis_label = inptxt.value
button.js_on_click(CustomJS(args=dict(inptxt=inptxt,
displaytxt=displaytxt,
# Need `[0]` because `p.xaxis` is actually
# a "splattable list" that BokehJS doesn't support.
xaxis=p.xaxis[0]),
code="""\
displaytxt.text = inptxt.value;
xaxis.axis_label = inptxt.value;
"""))
show(column(inptxt, displaytxt, button, p))
推荐阅读
- javascript - 搜索栏产生合成事件
- java - 我的 java 程序无法正常运行我希望它将几个数字输入一个数组并按从低到高的顺序放入另一个数组
- mysql - 为什么我的 ADO 结果集在使用 PreparedStatement 调用 StoredProcedure 时只给我一行?
- c - 自定义工具提示格式
- c - 减去两个 uint32_t 变量会产生一种溢出的结果?
- spring-boot - 忽略 bindingResult 验证中的字段
- sql-server - 将 SQL Server 2008 备份还原到 SQL Server 2016
- excel - 如何检查用户是否具有对文件夹的写入权限?
- c - 如何使用奇异容器在集群上运行 Kaldi 的 Timit 配方?
- c# - 如何覆盖 Bloomberg API RefData