Skip to main content
 首页 » 编程设计

python之如何将自定义 css 代码添加到由 python Bokeh、save() 生成的独立 HTML 文件

2024年11月01日18lautakyan007

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

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

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

但我找不到将 css 类注入(inject)输出 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) 

有什么建议吗?

请您参考如下方法:

最终我在文件创建后编辑了 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 但内部级别的类会覆盖其属性,因此不适用就我而言。