您的位置:首页 >Python-docx 设置页面大小的正确方法
发布于2026-01-28 阅读(0)
扫一扫,手机访问

在使用 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)
⚠️ 注意事项:
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 返回浮点英寸值。
总之,牢记 page_width 和 page_height 是属性而非方法——赋值即生效,调用则报错。这是 python-docx API 设计中典型的“属性式接口”,与 paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER 等风格一致。
上一篇:苹果手机隐藏相册文件夹方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9