pythonpywin32win32comautodeskautodesk-inventor

How to place parts into assemblys using Inventor via the API with Python


I'm trying to use the Inventor API with Python. I already managed to open new documents and modify existing parts, but now I'm trying to place components into an assembly, but it just doesn't work.

This is the simplified version of my code so far:

import win32com.client as win32
project_folder = "C:\\Users\\User_1\\210608_project\\"

#initialization
inv = win32.gencache.EnsureDispatch('Inventor.Application')
inv.Visible = True

#Open a new assembly
inv.Documents.Add(win32.constants.kAssemblyDocumentObject, "", True)
invActDoc = inv.ActiveDocument
invAssDoc = win32.CastTo(invActDoc, 'AssemblyDocument')
print('invAssdoc', type(invAssDoc))


#Create the transient matrix
oTG = inv.TransientGeometry
print(type(oTG), oTG)
oMatrix = oTG.CreateMatrix
print(type(oMatrix))

#Add component to assembly
invAssDocDef = invAssDoc.ComponentDefinition
invAssOcc = invAssDocDef.Occurrences
invAssOcc.Add(project_folder + 'generic_part.ipt', oMatrix)

Inventor and a new assembly are opening just fine, the transient matrix for the placement of the component ist created, but the placement itself does not work:

"C:\Program Files\Python37\python.exe"
C:/Users/User_1/210608_project/how_to_put_components_in_assemblies.py
invAssdoc <class 'win32com.gen_py.D98A091D-3A0F-4C3E-B36E-61F62068D488x0x1x0.AssemblyDocument.AssemblyDocument'>
<class 'win32com.gen_py.D98A091D-3A0F-4C3E-B36E-61F62068D488x0x1x0.TransientGeometry.TransientGeometry'> <win32com.gen_py.Autodesk Inventor Object Library.TransientGeometry instance at 0x1383360710136>
<class 'method'>
Traceback (most recent call last):
  File "C:/Users/User_1/210608_project/how_to_put_components_in_assemblies.py", line 24, in <module>
    invAssOcc.Add(project_folder + 'generic_part.ipt', oMatrix)
  File "C:\Users\User_1\AppData\Local\Temp\gen_py\3.7\D98A091D-3A0F-4C3E-B36E-61F62068D488x0x1x0\ComponentOccurrences.py", line 37, in Add
    , Position)
TypeError: The Python instance can not be converted to a COM object

Process finished with exit code 1

I think my error is somwhere in the way how I'm using win32com, but I'm really not sure, as i'm still fairly new to programming. If i try what seems to be the equivalent in VBA (https://forums.autodesk.com/t5/inventor-customization/vba-code-to-place-a-part-in-an-assembly/m-p/6379498#M64612) it works just fine, but i want to use Python (partly just for the heck of it, partly because it's part of a bigger project).


Solution

  • I'm not familiar with python, but it looks you miss brackets on this line oMatrix = oTG.CreateMatrix and you set oMatrix as reference to method, not its result. Try this oMatrix = oTG.CreateMatrix()