Python SolidWorks secondary development—SolidWorks four ways to traverse components (1)
Article directory
Preface
The traversal of components is mainly to facilitate subsequent operations on components, such as property modification of batch components, equation modification, etc. Here are four traversal methods that come with SolidWorks. This article introduces the first traversal method.
1. Official sample traversal code
In the SolidWorks official API help file, search for "Traverse Assembly at Component Level Example" to find specific sample code. The detailed sample code is as follows:
Option Explicit
Sub TraverseComponent _
(swComp As SldWorks.Component2, nLevel As Long)
Dim vChildComp As Variant
Dim swChildComp As SldWorks.Component2
Dim swCompConfig As SldWorks.Configuration
Dim sPadStr As String
Dim i As Long
For i = 0 To nLevel - 1
sPadStr = sPadStr + " "
Next i
vChildComp = swComp.GetChildren
For i = 0 To UBound(vChildComp)
Set swChildComp = vChildComp(i)
TraverseComponent swChildComp, nLevel + 1
Debug.Print sPadStr & swChildComp.Name2 & " <" & swChildComp.ReferencedConfiguration & ">"
Next i
End Sub
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swConf As SldWorks.Configuration
Dim swRootComp As SldWorks.Component2
Dim bRet As Boolean
Dim fileName As String
Dim errors As Long
Dim warnings As Long
Set swApp = CreateObject("SldWorks.Application")
Set swModel = swApp.ActiveDoc
Set swConf = swModel.GetActiveConfiguration
Set swRootComp = swConf.GetRootComponent3(True)
Debug.Print "File = " & swModel.GetPathName
' Traverse components
TraverseComponent swRootComp, 1
End Sub
2. Python traversal code
To facilitate subsequent comparison, the functions of the Python code and the functions of the VBA code remain the same and will not be deleted. The following is an example of the Python code:
import win32com.client
import pythoncom
from swconst import constants
def TraverseComponent(swComp, nLevel):
sPadStr=''
for i in range(nLevel-1):
sPadStr = sPadStr + " "
vChildComp = swComp.GetChildren
for i in range(len(vChildComp)):
swChildComp = vChildComp[i]
TraverseComponent(swChildComp, nLevel + 1)
print(f'{
sPadStr}{
swChildComp.Name2} " <" {
swChildComp.ReferencedConfiguration} ">"')
def main():
sldver=2018
swApp=win32com.client.Dispatch(f'SldWorks.Application.{
sldver-1992}')
swApp.CommandInProgress =True
swApp.Visible =True
swModel = swApp.ActiveDoc
swConf = swModel.GetActiveConfiguration
swRootComp = swConf.GetRootComponent3(True)
print(f"File = {
swModel.GetPathName}" )
# ' Traverse components
TraverseComponent(swRootComp, 1)
if __name__ == '__main__':
main()