Python SolidWorks 二次开发---SolidWorks四种遍历零部件的方式(三)

Python SolidWorks 二次开发—SolidWorks四种遍历零部件的方式(三)



前言

零部件的遍历主要是为了方便对零部件的后续操作,例如批量零部件的属性修改,方程式修改等,这里介绍四种SolidWorks自带的遍历方法,本文介绍第三种遍历方式,前两种种遍历链接方式如下
Python SolidWorks 二次开发—SolidWorks四种遍历零部件的方式(一)
Python SolidWorks 二次开发—SolidWorks四种遍历零部件的方式(二)


一、官方示例的遍历代码

在SolidWorks官方API帮助文件中,搜索“Expand or Collapse FeatureManager Design Tree Nodes Example”,可找到具体的示例代码,示例代码中包含很多筛选项,我们这里只是对零部件进行遍历,所以将示例代码进行修改,修改后的代码如下,此遍历的原理是通过查找遍历Node,然后查找Node类型为Component2类型进行遍历:

Option Explicit

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim myModel As SldWorks.ModelDoc2
    Dim featureMgr As SldWorks.FeatureManager
    Dim rootNode As SldWorks.TreeControlItem
    Set swApp = Application.SldWorks
    Set myModel = swApp.ActiveDoc
    Set featureMgr = myModel.FeatureManager
    Set rootNode = featureMgr.GetFeatureTreeRootItem()
    If Not rootNode Is Nothing Then
        traverse_node rootNode
    End If   
End Sub

Sub traverse_node(node As SldWorks.TreeControlItem)
    Dim childNode As SldWorks.TreeControlItem
    Dim componentNode As SldWorks.Component2
    Dim nodeObject As Object
    Dim refConfigName As String
    Set nodeObject = node.Object
    If Not nodeObject Is Nothing Then
        Set componentNode = nodeObject
        If componentNode.GetSuppression <> SwConst.swComponentSuppressionState_e.swComponentSuppressed Then
            Debug.Print componentNode.Name2
        End If        
    End If    
    Set childNode = node.GetFirstChild()
    While Not childNode Is Nothing
        If childNode.ObjectType = SwConst.swTreeControlItemType_e.swFeatureManagerItem_Component Then
            traverse_node childNode
        End If        
        Set childNode = childNode.GetNext
    Wend    
End Sub

二、Python遍历代码

此处为方便后续比较,Python代码功能和VBA代码功能保持一致,不进行删减,以下为Python代码示例:

import win32com.client
from swconst import constants

def traverse_node(node):
    nodeObject = node.Object
    if nodeObject is not None:
        if nodeObject.GetSuppression!=constants.swComponentSuppressed:
            print(nodeObject.Name2)
    childNode = node.GetFirstChild
    while childNode is not None:
        if childNode.ObjectType==constants.swFeatureManagerItem_Component:
            traverse_node(childNode)
        childNode = childNode.GetNext

def main():
    sldver=2018
    swApp=win32com.client.Dispatch(f'SldWorks.Application.{
      
      sldver-1992}')
    swApp.CommandInProgress =True
    swApp.Visible =True
    myModel = swApp.ActiveDoc
    featureMgr = myModel.FeatureManager
    rootNode = featureMgr.GetFeatureTreeRootItem2(constants.swFeatMgrPaneBottom)
    traverse_node(rootNode)

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/Bluma/article/details/129032702