使用python-docx设置docx文档背景色为蓝色却显示为黑色问题求助
问题原因
该问题由两处配置错误共同导致:
- 你同时为背景元素配置了
w:themeColor和w:themeTint属性,Word中主题色的优先级高于自定义十六进制颜色,你设置的text1主题色默认对应黑色,直接覆盖了你定义的蓝色值。 w:color属性不识别带#前缀的十六进制色值,需要直接传入6位十六进制字符。
解决方案
你不需要使用十六进制以外的其他颜色格式,仅需修正背景属性配置即可:
- 删除
w:themeColor、w:themeTint两行属性配置,避免主题色覆盖自定义颜色 - 移除
w:color赋值中的#前缀
修正后的对应代码段
shd = OxmlElement('w:background') # 仅需设置w:color属性,值为不带#的6位十六进制色值 shd.set(qn('w:color'), '0000FF') # Add background element at the start of Document.xml using below mydoc.element.insert(0, shd) # Add displayBackgroundShape element to setting.xml shd1 = OxmlElement('w:displayBackgroundShape') mydoc.settings.element.insert(0, shd1)
内容的提问来源于stack exchange,提问作者mrpy
相关产品推荐
相关产品推荐

