【问题标题】:How to make Bokeh button invoke a function (using CustomJS)如何让 Bokeh 按钮调用一个函数(使用 CustomJS)
【发布时间】:2020-08-04 18:22:43
【问题描述】:

我可以使用 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 的情况下实现它。非常感谢任何有关如何执行此操作的帮助。

【问题讨论】:

  • 为什么你首先需要摆脱curdoc
  • 我希望有一个可以启动和管理的 Python 程序,而不必处理烧瓶服务器和散景服务器。另外,我不知道在使用 Zappa 部署时如何处理散景 + 烧瓶。但是,关于如何解决我的上述问题的任何提示?
  • 您可以在独立脚本或将 Bokeh 作为库嵌入的应用程序中使用 curdoc。您的代码应该按原样工作,特别是考虑到回调与 curdoc 的使用正交。除非您的意思是您不想使用任何 服务器,包括bokeh serve 创建的服务器。这意味着,您只想使用静态 HTML 文件。在这种情况下是的,您需要使用 CustomJS 并将您的 Python 回调代码重写为 JavaScript。
  • 谢谢尤金。是的,我的意思是根本不必使用散景服务器。我不知道 CustomJS 但如果有人可以为上述代码提供等效的 customjs 版本,我可以尝试将其扩展到我的完整代码。希望它澄清。

标签: python bokeh


【解决方案1】:
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))

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多