如何保持形状的位置参数以使其在给定参数 "left" 的最左侧而不是中点?

How to keep shape's position parameters in order to keep it's left-most side at given parameter "left",but not mid point?

在使用 python-pptx 模块时,我了解到它将形状确定形状的中心放置在左侧参数中的给定长度处。假设我给了 shape = slide.shapes.add_textbox(Inches(1), top, width, height) 然后形状的中心点将放置在距左侧 1 英寸的位置。我想要做的是,形状的最左侧应放置在距幻灯片左侧 1 英寸的位置。因为现在如果我添加更多文本,大部分文本都会从幻灯片中移出。有什么办法吗?

我在 link 发现了类似的问题,但没有答案,因为问题被误解了,而且声誉不高,我不能在那里发表评论。

谢谢

形状的 .top.left 属性表示从幻灯片的 左上角 的距离形状的左上角。你认为形状位置是相对于形状中心的想法是错误的。

如果您的形状左侧有文字溢出,我会首先检查形状文本框架中每个段落的 Paragraph.alignment 设置:

from pptx.enum.text import PP_ALIGN

for paragraph in shape.text_frame.paragraphs:
    paragraph.alignment = PP_ALIGN.LEFT

如果段落右对齐,文本将向左对齐。

与此行为相关的另一个因素是 TextFrame.word_wrap 设置。如果关闭自动换行,文本可能会超出形状的水平范围。

shape.text_frame.word_wrap = True

Finally, the TextFrame.auto_size behaviors of a shape can cause relocation of the shape, in particular, when the "Resize shape to fit text" option is selected, one or更多的大小或位置属性已更改以符合要求。请注意,在选择哪一侧 "stretch" 形状以适合其文本时,此设置可以与段落对齐设置交互。

from pptx.enum.text import MSO_AUTO_SIZE

shape.text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT

您可能需要进行试验才能找到能够产生您想要的行为的组合。我会说最安全的起点是:

from pptx.enum.text import MSO_AUTO_SIZE
from pptx.enum.text import PP_ALIGN

shape = slide.shapes.add_textbox(Inches(1), top, width, height)
text_frame = shape.text_frame
text_frame.text = 'Text I want to appear in text-box'
text_frame.auto_size = MSO_AUTO_SIZE.NONE
text_frame.word_wrap = False
for paragraph in text_frame.paragraphs:
    paragraph.alignment = PP_ALIGN.LEFT

另请注意,LibreOffice 上与 Microsoft PowerPoint 上的自动调整大小行为可能略有不同。在上面的 "safe" 选项中情况并非如此,但要记住一些事情。