当前位置:首页>python>Python-CAD 指定区域批量修改图框属性

Python-CAD 指定区域批量修改图框属性

  • 2026-09-08 17:13:24
Python-CAD 指定区域批量修改图框属性

 🙋‍♀️ 本期工具展示具体

支持图框、或其他属性、属性块:
  • 属性内容
  • 比例因子
  • 高度

可指定区域操作,而不是全图查找替换。

--------------------

🔍背景

在图纸调整阶段,图框往往会发生变化。例如:

  • 图名变长,预留空间不足,需要缩小比例因子
  • 某个属性字段内容需要统一更新
  • 某个参数高度需要统一调整

常规做法是使用 FIND 查找替换。但 FIND 只能全图生效,无法限制在指定区域内。

当一张图中存在多个图框,或同一属性在不同区域有不同含义时,全局替换就会带来风险。

因此这个工具的目标不是简单替换字符串,而是:

允许用户框选指定区域的图框(块参照),只对该区域内的属性进行批量修改。

它解决的是“局部批量修改”的问题。

--------------------

💡实现思路

整体逻辑分为五步:

  1. 输入属性名称(Tag)
  2. 勾选需要修改的字段(内容 / 比例因子 / 高度)
  3. 在CAD中框选目标图框
  4. 遍历块参照中的属性
  5. 匹配Tag后执行修改

核心在于对 AcDbBlockReference 的属性进行访问和更新。


1. 连接CAD并获取当前文档

import win32com.clientzwcad = win32com.client.Dispatch("ZWCAD.Application")zwcad.Visible = Truedoc = zwcad.ActiveDocument

2. 指定区域选择图框

通过 SelectionSets 实现交互式选择。

selection_set = doc.SelectionSets.Add("MySelection")filter_type = [0]filter_data = ["INSERT"]   # 只允许选择块参照selection_set.SelectOnScreen(filter_type, filter_data)

3. 遍历块属性

块参照对象类型为:

AcDbBlockReference

AcDbBlockReference

获取其属性:

attributes=entity.GetAttributes()

然后遍历属性列表:

for attrib in attributes:    if attrib.TagString == property_name:

4. 执行修改

根据用户勾选情况修改对应字段。

if 'TextString' in to_modify:    attrib.TextString = to_modify['TextString']if 'ScaleFactor' in to_modify:    attrib.ScaleFactor = to_modify['ScaleFactor']if 'Height' in to_modify:    attrib.Height = to_modify['Height']attrib.Update()

5. 修改逻辑核心函数

下面是核心批量修改函数:

def modify_attribute(self, property_name, to_modify):    zwcad = win32com.client.Dispatch("ZWCAD.Application")    zwcad.Visible = True    doc = zwcad.ActiveDocument    try:        selection_set = doc.SelectionSets.Item("MySelection")        selection_set.Delete()    except Exception:        pass    selection_set = doc.SelectionSets.Add("MySelection")    filter_type = [0]    filter_data = ["INSERT"]    selection_set.SelectOnScreen(filter_type, filter_data)    modified = 0    for entity in selection_set:        if entity.EntityName == "AcDbBlockReference":            attributes = entity.GetAttributes()            for attrib in attributes:                if attrib.TagString == property_name:                    if 'TextString' in to_modify:                        attrib.TextString = to_modify['TextString']                    if 'ScaleFactor' in to_modify:                        attrib.ScaleFactor = to_modify['ScaleFactor']                    if 'Height' in to_modify:                        attrib.Height = to_modify['Height']                    attrib.Update()                    modified += 1    selection_set.Delete()    return modified

与 FIND 的区别

功能
FIND
本工具
查找范围
全图
指定区域
是否支持比例因子
否
支持
是否支持高度
否
支持
是否支持块属性
部分
完全支持

因此它更适用于图框类属性批量调整。


它和前面的“下划线重建工具”一样,属于工具箱中的一个。

--------------------

🚀开始摸鱼!

🙋‍♀️ 作者:leilei

💫 碎碎念学习记录

📅 更新时间:2026年4月

最新文章

随机文章