我正在尝试使用Python和pywin32自动执行AutoCAD中的某些任务。 AutoCAD版本为2018。
我尝试遵循AutoCAD文档中显示的方法:http://help.autodesk.com/view/ACD/2018/ENU/?guid=GUID-A5B6ACC4-DCD8-4FE2-AB06-D3C3C349475B
我想选择一个特定的块,然后编辑其某些属性。
我的代码:
acad = win32com.client.Dispatch("AutoCAD.Application")
acad.ActiveDocument = acad.Documents.Open(os.path.normpath(os.path.join(baseDir,filename)))
time.sleep(2)
doc = acad.ActiveDocument # Document object
entity = doc.Blocks.Item('TTLB ATTRIBUTES')
print entity.Name
print entity.HasAttributes
这将正确打印块名称,但是尝试访问HasAttributes属性会导致此错误:
AttributeError: Item.HasAttributes
如果我更改代码以简单地遍历所有对象,那么它将起作用:
acad = win32com.client.Dispatch("AutoCAD.Application")
acad.ActiveDocument = acad.Documents.Open(os.path.normpath(os.path.join(baseDir,filename)))
time.sleep(2)
doc = acad.ActiveDocument # Document object
for entity in doc.PaperSpace:
if entity.EntityName == 'AcDbBlockReference':
if entity.Name == 'TTLB ATTRIBUTES':
print entity.Name
print entity.HasAttributes
我不明白第二个为什么起作用而第一个不起作用。当我阅读文档时,似乎他们俩都应该找到同一个对象。
答案 0 :(得分:1)
在Item
上调用Blocks collection方法时,您将获得一个Block Definition对象(AcDbBlockTableRecord
),该对象是构成块的一组对象的容器几何,并且不具有HasAttributes
属性。
在迭代Paperspace Collection所拥有的对象(其本身是一种块定义)时,您遇到Block Reference个对象(AcDbBlockReference
),该对象 具有HasAttributes
属性。
考虑到“块定义”本质上是该块的“蓝图”,并且每个“块参考”都是一个实例,该实例显示在块定义中找到的对象,在图形中的特定位置,比例,旋转和方向。
属性在块定义中也有Attribute Definitions,并且在每个块参考上附加了相应的Attribute References。然后,对于插入到图形中的每个块参考,此类属性参考可以保留不同的文本内容。
此外,有趣的是,属性引用也可以通过编程方式附加到块引用,而与块定义无关,但是,使用标准的即用型前端操作AutoCAD时,这是不允许的。
使用上述信息,您将需要遍历在相关布局容器中找到的块引用,并且,如果该块引用符合您的条件,则可以遍历该块引用所拥有的一组属性引用(您可以使用GetAttributes
方法获得),更改那些符合您条件的属性的Textstring
属性。