python-pptx:将幻灯片超链接添加到 table 个单元格

python-pptx: adding slide hyperlinks to table cells

图书馆的 click_action 功能仅支持 BaseShape class 成员(table 单元格、文本框、段落和 运行s不是)。同时一个文本运行的hyperlink属性只支持外部(web-)link的设置。如何将内部 link 添加到 table 内的幻灯片,例如创建 table-of-contents?

下面的代码解决了上面的问题:

from lxml import etree  # type: ignore
from pptx.opc.constants import RELATIONSHIP_TYPE  # type: ignore

def link_table_cell_to_slide(table_shape, cell, slide):
    # pylint: disable=protected-access
    rel_id = table_shape._parent.part.relate_to(slide.part, RELATIONSHIP_TYPE.SLIDE)
    link_run = cell.text_frame.paragraphs[0].runs[0]
    nsmap = link_run._r.nsmap
    # trying to do it with format strings and escaping curly braces
    # was not doable with pylint (unignorable syntax error)
    ns_a = '{' + nsmap['a'] + '}'
    ns_r = '{' + nsmap['r'] + '}'
    run_properties = link_run._r.find(f'{ns_a}rPr')
    hlink = etree.SubElement(run_properties, f'{ns_a}hlinkClick')
    hlink.set('action', 'ppaction://hlinksldjump')
    hlink.set(f'{ns_r}id', rel_id)

# ... determining the toc_shape, row in the table to link up as well as
# the target slide to link to
link_table_cell_to_slide(toc_shape, row.cells[0], target_slide)