用已知的幻灯片索引和shape_id替换图表中的数据



我想更新条形图中的数据,但在访问包含该图表的对象时出错。这是给我shape_id:的代码

shp=prs.slides[0].shapes
for shape in shp:
print(
"id: %s, type: %s, name: %s"
% (shape.shape_id, shape.shape_type, shape.name)
)
# => **Output:** id: 7, type: CHART (3), name: Chart 6

但是,当我尝试使用shape_id来定义图表对象时,我得到了以下错误:chart=prs.幻灯片[0].形状[7].图表

错误:

raise IndexError("shape index out of range")
IndexError: shape index out of range

我也试过这个代码:chart=shp_spTree.shape_id[7]chart

错误:

TypeError: 'int' object is not subscriptable

问题是您将shape id用作shape序列中的索引。形状id与该形状在形状"列表"中的位置不对应。

要按id(或名称(查找形状,您需要这样的代码:

def find_shape_by_id(shapes, shape_id):
"""Return shape by shape_id."""
for shape in shapes:
if shape.shape_id == shape_id:
return shape
return None

或者,如果你做了很多,你可以用一个dict来做这项工作:

shapes_by_id = dict((s.shape_id, s) for s in shapes)

然后,它为您提供了所有方便的dict方法,如:

>>> 7 in shapes_by_id
True
>>> shapes_by_id[7]
<pptx.shapes.Shape object at 0x...>

最新更新