我希望使用OpenURL从bokeh中打开URL,但要从按钮的回调中打开,而不要使用taptool。下面的代码重现了我遇到的问题,即在使用带有OpenURL的taptool时可以打开新选项卡,但是当我在按钮回调中使用OpenURL时却没有任何反应。(很多示例来自bokeh docs:http://docs.bokeh.org/en/0.12.5/docs/user_guide/examples/interaction_open_url.html)
from bokeh.models import ColumnDataSource, OpenURL, TapTool
from bokeh.models.widgets import Button
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import column, widgetbox
from bokeh.io import curdoc
p = figure(plot_width=400, plot_height=400,
tools="tap", title="Click the Dots")
source = ColumnDataSource(data=dict(
x=[1, 2, 3, 4, 5],
y=[2, 5, 8, 2, 7],
color=["navy", "orange", "olive", "firebrick", "gold"]
))
p.circle('x', 'y', color='color', size=20, source=source)
url = "http://www.colors.commutercreative.com/@color/"
taptool = p.select(type=TapTool)
taptool.callback = OpenURL(url=url)
button = Button(label="Generate", button_type="success")
def button_callback():
print('button callback')
OpenURL(url="http://www.google.com")
button.on_click(button_callback)
doc = curdoc()
doc.add_root(column([p,widgetbox(button)]))
doc.title = "Hello World"
谢谢!
OpenURL
是CustomJS
的自定义版本,因此它仅在JavaScript中运行。它也是一个类,而不是一个函数-您不仅可以构造一个类OpenURL
的对象,还必须使用其其他方法来使其工作。
话虽如此,您不能将其与Button
一起使用,因为OpenURL
希望数据源替换URL中的所有占位符。而且Button
不能有数据源。
相反,您需要的是常规CustomJS
:
button.js_on_click(CustomJS(code="window.open('http://www.google.com')"))
而且您不需要bokeh serve
即可使其工作-即使在通过调用save
或show
生成的静态网页上也可以使用。