如何使Bokeh按钮调用函数(使用CustomJS)

2024-09-26 22:49:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用curdoc选项获得功能,然后使用“bokeh serve bokehcode.py”,然后让我的烧瓶代码(称为app.py)引用此bokeh图。 但是我需要一个包含bokeh部分的python代码,我遇到了一个问题,那就是让按钮点击来调用更新我的绘图/图形的函数。我一整天都没怎么走运

为了简单起见,我删除了所有的功能(甚至是烧瓶部分),并在下面放了一个简化的代码,我需要在没有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的情况下实现它。非常感谢您为我们提供的帮助


Tags: 代码frompyimport功能绘图烧瓶选项
1条回答
网友
1楼 · 发布于 2024-09-26 22:49:47
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))

相关问题 更多 >

    热门问题