在 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 等页

✅ 正确用法是直接赋值:
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) # ✅ 这行对,但上一行已破坏对象状态,可能导致后续异常
⚠️ 注意事项:
? 小技巧:可通过 print(type(section.page_width)) 验证其类型(输出
总结:牢记——python-docx 的页面布局参数是属性,不是方法。赋值即生效,无需括号调用。这是初学者高频踩坑点,修正后即可稳定控制文档版式。