首页 > 解决方案 > 使用 python-docx 添加图片标题

问题描述

我使用 python-docx 生成一个 Microsoft Word 文档,其中包含一个带有图像的表格。以下代码块显示了将图像添加到表中的 for 循环:

        row_num = 2
        img_cnt = 0
        for i, var in enumerate(img_list_obj):
            img = "img/NO-" + str(technical_object) + "/" + img_list_obj[i]
            img_cnt = img_cnt + 1
            row = table.rows[row_num].cells

            if (img_cnt % 2) != 0:
                paragraph = row[0].paragraphs[0]
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                table.cell(row_num, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
                run = paragraph.add_run()
                run.add_picture(img, width=Cm(7.50), height=Cm(5.50))
            else:
                paragraph = row[1].paragraphs[0]
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                table.cell(row_num, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
                run = paragraph.add_run()
                run.add_picture(img, width=Cm(7.50), height=Cm(5.50))
                if i + 1 != len(img_list_obj):
                    table.add_row()
                    row = table.rows[row_num + 1].cells
                    row_num = row_num + 1

有没有办法给图片添加标题?我对 Python 和 python-docx 比较陌生,但我找不到关于这个主题的任何文档。

非常感谢!约书亚

标签: pythonimagepython-docx

解决方案


似乎 python-docx 不支持图像标题。当您调用add_picturean时,根据文档InlineShape返回。的文档没有提到任何关于字幕的内容。事实上,唯一一次提到标题是在文本样式的上下文中。此外,python-docx 存储库中有一个关于此限制的未解决问题。InlineShape


推荐阅读