Python-docx 中设置页面尺寸的正确方法:使用属性赋值而非函数调用

Python-docx 中设置页面尺寸的正确方法:使用属性赋值而非函数调用

python-docx 中,设置页面宽度和高度时,`section.page_width` 和 `section.page_height` 是可读写属性(而非方法),错误地将其当作函数调用(如 `section.page_width(inches(5))`)会导致 `’twips’ object is not callable` 异常。

python-docx 的 Section 对象中,page_width、page_height、left_margin、right_margin 等页面布局相关字段均为属性(property),其底层类型为 Twips(以二十分之一磅为单位的整数),但对外暴露为支持 Inches、Cm、Pt 等 Length 类型的可赋值属性。

✅ 正确用法是直接赋值:

from docx import Document
from docx.shared import Inches

doc = Document()
section = doc.sections[0]

# ✅ 正确:直接赋值(属性设置)
section.page_width = Inches(5)
section.page_height = Inches(5)
section.left_margin = Inches(0.75)
section.right_margin = Inches(0.75)

❌ 错误用法(引发 ‘Twips’ object is not callable):

section.page_width(Inches(5))  # TypeError: 'Twips' object is not callable
section.page_height = Inches(5)  # ✅ 这行对,但上一行已破坏对象状态,可能导致后续异常

⚠️ 注意事项:

图星人

图星人

好用的AI生图工具,百万免费商用图库

下载

立即学习Python免费学习笔记(深入)”;

  • Twips 是 python-docx 内部使用的不可变长度单位类,不可被调用(即不支持 () 操作符);
  • 所有 section.*_margin、section.header_distance、section.footer_distance 等同理,均需用 = 赋值,而非函数调用;
  • 若需批量设置页面布局,建议在获取 section 后统一赋值,避免中间状态不一致;
  • 修改页面尺寸后,若文档已含内容,Word 应用程序会自动重排,但部分复杂格式(如分栏、文本框)可能需手动校验显示效果。

? 小技巧:可通过 print(type(section.page_width)) 验证其类型(输出 red.Twips’>),进一步确认它不是 callable 对象。

总结:牢记——python-docx 的页面布局参数是属性,不是方法。赋值即生效,无需括号调用。这是初学者高频踩坑点,修正后即可稳定控制文档版式。

https://www.php.cn/faq/2027844.html

发表回复

Your email address will not be published. Required fields are marked *