Pyvis网络选项设置报错:'dict'无'physics'属性求解决
问题分析
你遇到的AttributeError是因为调用顺序冲突导致:执行net.set_options()传入自定义JS配置字符串后,Pyvis会将self.options从原生的Option对象转换为普通字典;而barnes_hut()方法依赖Option对象的physics属性完成配置,字典没有该属性,因此触发报错。
解决方案
提供两种可行修复方式:
方式1:调整调用顺序,先配置物理引擎再设置自定义选项
先调用barnes_hut()(此时self.options还是Option对象),再通过set_options()补充其他自定义配置。注意自定义配置中的physics部分会覆盖barnes_hut()的对应参数,需按需调整:
# 初始化网络 net = Network(height='1000px',width='80%',bgcolor='#222222',filter_menu=True,select_menu=True, notebook=True,cdn_resources='remote',font_color="white") # 先调用barnes_hut配置物理引擎参数 net.barnes_hut(gravitationalConstant=-80000, springLength=250, springConstant=0.001) # 再设置自定义选项,保留nodes、edges配置,以及physics中未被覆盖的minVelocity net.set_options(''' const options = { "nodes": { "borderWidth": null, "borderWidthSelected": null, "opacity": null, "size": null }, "edges": { "arrows": { "to": { "enabled": true } }, "color": { "inherit": true }, "selfReferenceSize": null, "selfReference": { "angle": 0.7853981633974483 }, "smooth": { "forceDirection": "none" } }, "physics": { "minVelocity": 0.75 } }''') # 后续添加节点、边的代码保持不变 # Add center nodes net.add_nodes(selected_nodes[number[0]:number[1]],title = ['1' for i in range(number[0],number[1])],\ color = ['#FFA500' for i in range(number[0],number[1])],\ label = [nodes[selected_nodes[i]] for i in range(number[0],number[1])],size = [degrees[selected_nodes[i]] for i in range(number[0], number[1])]) ...
方式2:移除barnes_hut()调用,完全通过自定义配置管理
你的set_options()中已经完整定义了barnesHut的物理参数,无需再调用barnes_hut()方法,直接删除该调用即可:
net = Network(height='1000px',width='80%',bgcolor='#222222',filter_menu=True,select_menu=True, notebook=True,cdn_resources='remote',font_color="white") net.set_options(''' const options = { "nodes": { "borderWidth": null, "borderWidthSelected": null, "opacity": null, "size": null }, "edges": { "arrows": { "to": { "enabled": true } }, "color": { "inherit": true }, "selfReferenceSize": null, "selfReference": { "angle": 0.7853981633974483 }, "smooth": { "forceDirection": "none" } }, "physics": { "barnesHut": { "gravitationalConstant": -80000, "springLength": 250, "springConstant": 0.001 }, "minVelocity": 0.75 } }''') # 删除此行:net.barnes_hut() # 后续添加节点、边的代码保持不变 ...
说明
- 方式1适合希望利用
barnes_hut()简化参数配置,同时补充自定义样式的场景; - 方式2更简洁,所有配置统一通过
set_options()管理,彻底避免对象类型冲突问题。
内容的提问来源于stack exchange,提问作者Red_Brick
相关产品推荐
相关产品推荐

