如何在python-pptx生成的PPTX中控制幻灯片标题字体大小?
解决python-pptx修改幻灯片标题字号时的AttributeError问题
你遇到的AttributeError: 'SlidePlaceholder' object has no attribute 'font'错误,核心原因是slide.shapes.title返回的是占位符容器对象,而非直接可设置字体的文本对象。字体属性需要通过占位符内部的文本框段落来修改。
正确修改方式
将代码中出错的行:
title_shape.font.size = Pt(32)
替换为:
title_shape.text_frame.paragraphs[0].font.size = Pt(32)
如果你的标题文本可能包含多行,也可以遍历所有段落统一设置字号:
for paragraph in title_shape.text_frame.paragraphs: paragraph.font.size = Pt(32)
修改后的完整代码
import tkinter as tk from tkinter import filedialog from pptx import Presentation from pptx.util import Pt import os def create_presentation(): # 打开文件选择对话框 root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() # 读取文本文件获取幻灯片标题 with open(file_path) as f: slide_titles = f.read().splitlines() # 创建新的PPT演示文稿 prs = Presentation() # 使用标题和内容版式(索引1) title_and_content_layout = prs.slide_layouts[1] # 为每个标题添加幻灯片 for title in slide_titles: # 移除标题前的连字符或空格 title = title.lstrip('- ') slide = prs.slides.add_slide(title_and_content_layout) title_shape = slide.shapes.title title_shape.text = title # 正确设置标题字号为32pt title_shape.text_frame.paragraphs[0].font.size = Pt(32) # 可在此添加内容文本,或留空 # content_shape = slide.placeholders[1] # content_shape.text = "say something here" # 生成输出路径 dir_path = os.path.dirname(file_path) file_name = os.path.basename(file_path) base, ext = os.path.splitext(file_name) new_file_name = base + ".pptx" output_path = os.path.join(dir_path, new_file_name) # 保存演示文稿 prs.save(output_path) root.destroy() create_presentation()
原理说明
在python-pptx中,占位符(Placeholder)是幻灯片上的内容容器,文本内容实际存储在其text_frame属性中。每个文本框包含若干段落(Paragraph),字体样式需要针对段落或段落内的字符块(Run)进行设置。标题占位符默认仅包含一个段落,因此直接访问paragraphs[0]即可修改整个标题的字号。
内容的提问来源于stack exchange,提问作者edoft
相关产品推荐
相关产品推荐

