将图层添加到其他数据框时的ValueError

时间:2017-04-11 14:01:50

标签: python arcpy

我正在尝试编写一个脚本,将Austin_TX.mxd中Parks数据框中的park图层添加到同一地图文档中的其他两个数据框。

这是我的脚本,但我一直得到一个ValueError:Object:CreateObject Layer无效的数据源

import arcpy
mxd = arcpy.mapping.MapDocument(r"E:/Python/Homework8/Exercise10/Austin_TX.mxd")
dfList = arcpy.mapping.ListDataFrames(mxd, "Parks")
addLayer = arcpy.mapping.Layer("parks.lyr")
for df in dfList:
    arcpy.mapping.AddLayer(df, addLayer, "BOTTOM")
mxd.saveACopy(r"E:/Python/Homework8/Exercise10/Austin_TX.mxd")
del mxd, addLayer

我得到的错误是:

Traceback (most recent call last):
  File "E:/Python/Homework8/Exercise10/Results/HW8_Ch1.py", line 4, in <module>
    addLayer = arcpy.mapping.Layer("parks.lyr")
  File "C:\Program Files (x86)\ArcGIS\Desktop10.4\ArcPy\arcpy\arcobjects\mixins.py", line 402, in __init__
    super(LayerMixin, self).__init__(lyrfile)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.4\ArcPy\arcpy\arcobjects\_base.py", line 47, in __init__
    for arg in args))
ValueError: Object: CreateObject Layer invalid data source 

1 个答案:

答案 0 :(得分:0)

A Layer object旨在引用磁盘上的图层文件,而不是地图文档(MXD)中的图层。

要使用MXD中的图层,请使用ListDataFramesListLayers

df = arcpy.mapping.ListDataFrames(mxd, "Parks")[0]
addLayer = arcpy.mapping.ListLayers(mxd, "parks.lyr", df)[0]