首页 > 解决方案 > 如何让 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 的情况下实现它。非常感谢有关如何执行此操作的任何帮助。

标签: pythonbokeh

解决方案


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))

推荐阅读