使用 Python-pptx 居中对齐文本 [英] Center-align text with Python-pptx

查看:111
本文介绍了使用 Python-pptx 居中对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之问题:是否可以在 Python-pptx 中将文本居中对齐?

Question in short: Is it possible to align text to the center in Python-pptx?

自从我使用 Python-pptx 以来,我已经能够自动化很多事情,我真的很喜欢使用它!但是,我遇到了一个问题.我试图在幻灯片上水平居中我的文本.如果你不明白我的意思:

Since I'm using Python-pptx, I have been able to automate quite a lot of things and I really enjoy using it! However, I've run into a problem. I'm trying to center my text horizontally on a slide. If you don't understand me:

我的文字现在左对齐,类似于前两段的文字.但是,我希望它们与中心对齐,就像最后两段一样.这是我的代码片段:

My text is now aligned to the left, similar to the text in the first two paragraphs. However, I'd like them to be aligned to the center, like those last two paragraphs. This is a snippet of my code:

left = Cm(3)
top = Cm(2.5)
width = Cm(15)
height = Cm(1)
txBox = slide.shapes.add_textbox(left, top, width, height)
tf = txBox.text_frame
p = tf.add_paragraph()
run = p.add_run()
run.text = "Just an example"
font = run.font
font.size = Pt(30)

我查看了文档,但找不到任何有用的信息.我读了一些关于MSO_VERTICAL_ANCHOR"和PP_PARAGRAPH_ALIGNMENT"的内容,但我无法让它工作.

I looked in the documentation, but couldn't find anything useful. I read something about "MSO_VERTICAL_ANCHOR" and "PP_PARAGRAPH_ALIGNMENT", but I just can't get it working.

先谢谢你!

推荐答案

from pptx.enum.text import PP_ALIGN

shape.paragraphs[0].alignment = PP_ALIGN.CENTER

这直接取自 Python pptx 文档.这不适合你吗?您在问题中说您听说过 PP_PARAGRAPH_ALIGNMENT 但无法使其正常工作.出现了哪些问题?

This is taken directly from the Python pptx Docs. Does this not work for you? You said in your question that you've heard of PP_PARAGRAPH_ALIGNMENT but can't get it working. What problems are arising?

您可以在此处查看有关 Python pptx 对齐的更多信息.

在我下方评论的 Scanny 添加了一个很好的观点,可以解决您的问题:

Scanny, who commented below me added a wonderful point that will solve your problem:

段落对齐(也称为对齐)是段落的一个属性,必须单独应用于每个段落.在您的问题中包含的代码中,如果您添加一行 p.alignment = PP_ALIGN.CENTER 您应该得到您想要的.

Paragraph alignment (also known as justification) is a property of a paragraph and must be applied individually to each paragraph. In the code you included in your question, if you add a line p.alignment = PP_ALIGN.CENTER you should get what you're after.

这篇关于使用 Python-pptx 居中对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆