
在使用 python-docx 修改 word 文档页面尺寸时,page_width 和 page_height 是可读写的属性(而非方法),错误地将其当作函数调用会导致 'twips' object is not callable 异常。
python-docx 的 Section 对象中,page_width 和 page_height 是 Length 类型的属性(底层为 Twips 实例),用于表示页面尺寸。它们不支持函数调用语法(如 section.page_width(...)),而应直接赋值。常见误区正是将属性误写为方法调用,从而触发该错误。
✅ 正确写法如下:
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()、Cm()、Pt() 等单位构造器返回的是 Length 对象,可直接赋给 page_width / page_height;
- 修改后需调用 doc.save("output.docx") 才能持久化生效;
- 页面尺寸单位必须为 Length 类型(不能传入原始数字或字符串);
- 若需同时设置页边距、纸张方向等,可一并配置:
section.orientation = WD_ORIENT.LANDSCAPE # 需 from docx.enum.section import WD_ORIENT section.left_margin = Inches(0.75) section.right_margin = Inches(0.75)
? 小贴士:可通过 print(section.page_width) 查看当前值(返回 Twips 对象),其 .inches、.cm 等属性可方便转换查看,例如 section.page_width.inches 返回浮点英寸值。
立即学习“Python免费学习笔记(深入)”;
总之,牢记 page_width 和 page_height 是属性而非方法——赋值即生效,调用则报错。这是 python-docx API 设计中典型的“属性式接口”,与 paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER 等风格一致。










