【问题标题】:How to add custom css code to a standalone HTML file generated by python Bokeh, save()?如何将自定义 css 代码添加到由 python Bokeh、save() 生成的独立 HTML 文件中?
【发布时间】:2019-08-25 20:36:36
【问题描述】:

我正在创建可移植的 HTML 文件,这些文件使用 python bokeh 可视化一些数据。我使用一些按钮(切换小部件)来显示/隐藏绘图元素组(线、圆等)。 问题是按钮只有 4 种颜色可用,而且很难区分活动按钮和非活动按钮。

我决定动态编辑散景 css 类或添加我自己的类。 Toggle 类可以选择使用 bokeh 内置 css 类:

button = Toggle(label="Button 1", button_type="primary", css_classes=['some_class'])

但我找不到将 css 类注入输出 HTML 的方法。 有一个 bokeh.resources 类具有一些有趣的属性,例如 js_raw, css_raw 但我无法修改它们:

from bokeh.resources import Resources
my_css_class = """
.some_class {
  background-color: black;
  color: white;
  margin: 20px;
  padding: 20px;
} 
"""
res = Resources(js_raw="<style>{}</style".format(my_css_class))
#or
res = Resources(css_raw=my_css_class)
#or
setattr(res, 'css_raw', my_css_class)

没用:( 返回:“AttributeError:无法设置属性”

完整代码:

from bokeh.models.widgets import Toggle
from bokeh.io import save
from bokeh.plotting import figure, output_file
from bokeh.models import CustomJS
from bokeh.layouts import Column
from bokeh.resources import Resources


output_file('a.html')

N_lines = 10
x = range(3) 
fig = figure() 

# adding custom CSS class - if the button does not appear - it works:)
my_css_class = """
.some_class {
  display:none;
} 
"""
res = Resources(mode='inline', version=None, root_dir=None, minified=False, log_level='info', root_url=None, path_versioner=None, components=None)
# !!!!!!!!! line below does not add the class, toggle button still appears
res.css_raw.append(my_css_class)

# !!!!!!!!!!!!!! line below produces the error:
setattr(res, 'css_raw', my_css_class)
# ---------------------------------------------------------------------------
# AttributeError                            Traceback (most recent call last)
# <ipython-input-119-f642d1ca6dc6> in <module>
#      24 
#      25 # !!!!!!!!!!!!!! line below produces the error:
# ---> 26 setattr(res, 'css_raw', my_css_class)
#      27 # ---------------------------------------------------------------------------
#      28 # AttributeError                            Traceback (most recent call last)
#
# AttributeError: can't set attribute


callback_code = """
    active = cb_obj.active;
"""
args = [] 

for i in range(N_lines): 

    glyph = fig.line(
        x=x, 
        y=[random() for j in x], 
        color=choice(Category20_20), 
        legend=str(i)
    ) 
    args += [('line{}'.format(str(i)), glyph)]
    callback_code += "line{}.visible = active;".format(str(i))


toggle = Toggle(label="Hide All", button_type="success", active=True, css_classes=['some_class'])
toggle.callback = CustomJS(
    args={key:value for key,value in args},
    code=callback_code
)
fig.legend.click_policy='hide'

children = [fig, toggle]
col = Column(children=children)

save(col, resources=res)

有什么建议吗?

【问题讨论】:

  • res = Resources() res.js_raw.append('text') res.css_raw.append('text') save(..., resources=res) ?
  • 您可以在保存后使用自己的

标签: python css bokeh


【解决方案1】:

最终我在文件创建后编辑了 HTML 文件的标签。 (是的,这很丑陋,但它有效:)) 现在,您绝对可以区分按下(活动)和未按下(非活动)按钮。

from bs4 import BeautifulSoup
# need to defile paths to HTML files: FILE_IN and FILE_OUT

with open(FILE_IN,'r') as file_in:
    soup = BeautifulSoup(file_in.read())


old_style_primary = ".bk-root .bk-btn-primary.bk-active{background-color:#3276b1;border-color:#285e8e}"
new_style_primary = ".bk-root .bk-btn-primary.bk-active{background-color:#3276b1;border-color:#000000; border-width: 2px;}"

old_style_success = ".bk-root .bk-btn-success.bk-active{background-color:#47a447;border-color:#398439}"
new_style_success = ".bk-root .bk-btn-success.bk-active{background-color:#47a447;border-color:#000000; border-width: 2px;}"

old_style_warning = ".bk-root .bk-btn-warning.bk-active{background-color:#ed9c28;border-color:#d58512}"
new_style_warning = ".bk-root .bk-btn-warning.bk-active{background-color:#ed9c28;border-color:#000000; border-width: 2px;}"

old_style_danger = ".bk-root .bk-btn-danger.bk-active{background-color:#d2322d;border-color:#ac2925}"
new_style_danger = ".bk-root .bk-btn-danger.bk-active{background-color:#d2322d;border-color:#000000; border-width: 2px;}"

styles = soup.findAll('style')

style_string = str(styles[0]).replace("</style>","").replace("<style>","")
style_string = style_string.replace(old_style_primary, new_style_primary).replace(old_style_success, new_style_success).replace(old_style_warning, new_style_warning).replace(old_style_danger, new_style_danger)

styles[0].clear()
styles[0].insert(0, style_string)

with open(FILE_OUT,'w') as file_out:
    file_out.write(str(soup))

使用 css_classes=['some_class']some_class 应用于更高级别的 div,但内部级别的类会覆盖其属性,因此这不适用于我的情况。

【讨论】:

    猜你喜欢
    • 2016-05-21
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多