
在使用 python-docx 修改页面宽度或高度时,常见错误是将 `page_width` 和 `page_height` 当作可调用方法(如 `section.page_width(...)`),而实际上它们是可赋值的属性,需直接赋值 `inches()` 对象。
python-docx 库中,文档的页面布局参数(如页宽、页高、页边距等)均以属性(property)形式暴露,而非方法(method)。因此,对 section.page_width 或 section.page_height 使用圆括号调用会触发 TypeError: 'Twips' object is not callable —— 因为底层 Twips 类型对象不支持调用操作。
✅ 正确写法如下:
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)
⚠️ 注意事项:
- Inches() 是 python-docx 提供的单位封装类,也可使用 Cm()、Pt() 或原始 Twips 值(1 inch = 1440 twips),但推荐使用语义化单位;
- 修改 page_width/page_height 后,若需同步调整页边距以避免内容溢出,建议一并检查 section.left_margin、section.right_margin 等;
- doc.sections 默认至少包含一个节(Section),无需显式调用 add_section() 即可访问 doc.sections[0];
- 所有尺寸属性均为 Length 类型实例(如 Inches(5) 返回 Length 对象),不可传入浮点数或字符串。
? 小技巧:可通过 print(section.page_width.inches) 验证设置是否生效。
立即学习“Python免费学习笔记(深入)”;
总结:牢记 page_width、page_height、top_margin 等均为可读写属性,而非函数——这是避免 'Twips' object is not callable 错误的关键。











