您的位置:首页 >Python-docx 设置页面尺寸的正确方式
发布于2026-02-05 阅读(0)
扫一扫,手机访问

在 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) # ✅ 这行对,但上一行已破坏对象状态,可能导致后续异常
⚠️ 注意事项:
? 小技巧:可通过 print(type(section.page_width)) 验证其类型(输出 <class 'docx.shared.Twips'>),进一步确认它不是 callable 对象。
总结:牢记——python-docx 的页面布局参数是属性,不是方法。赋值即生效,无需括号调用。这是初学者高频踩坑点,修正后即可稳定控制文档版式。
上一篇:飞飞重逢首领打法及挑战技巧
下一篇:3DS Max快速制作马桶教学
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9