你碰到的这个错误:
code Copy code
AttributeError: Attribute active_view not found (tried lookup as a child widget)
是因为在调用 KLayout 的主窗口时对象层级的访问方式不对。这个错误通常是出现在使用 pya.Application.instance().main_window().active_view(),或类似写法时,但并没有找到你想访问的对象属性,原因可能是当前界面中没有打开版图,或方法使用得不正确。
✅ 正确的方式(推荐使用 current_view() 和 active_cellview()):
为了避免类似问题,这里给出正确且稳健的改进版脚本 :
✅ 修正后的完整脚本:将 polygon 转为 width=0 的 path
python Copy code
import pya
# 获取当前应用和主窗口中的视图
app = pya.Application.instance()
mw = app.main_window()
# 获取当前视图
layout_view = mw.current_view()
if layout_view is None:
raise Exception("没有打开任何布局窗口,请先打开一个 GDS 文件")
# 获取当前 cell
cv = layout_view.active_cellview()
if cv is None:
raise Exception("没有激活的 cell 视图")
layout = cv.layout()
top_cell = cv.cell()
# 指定要操作的层次(请根据需要修改 LayerInfo(lay, dat))
layer_info = pya.LayerInfo(1, 0) # 图层 1/0
layer_index = layout.layer(layer_info)
# 获取目标 shape list
shapes = top_cell.shapes(layer_index)
# 收集 polygon 并转为 path
polygons_to_convert = []
for shape in shapes.each():
if shape.is_polygon():
polygons_to_convert.append(shape.polygon)
# (可选)清除原有图层图形
# shapes.clear()
# 插入 path 替代 polygon
for polygon in polygons_to_convert:
pts = list(polygon.each_point())
# 移除最后一个点(闭合 polygon 的重复点)
if pts[0] == pts[-1]:
pts = pts[:-1]
if len(pts) >= 2:
path = pya.Path(pts, 0) # 宽度设为 0
shapes.insert(path)
print("✅ 所有 polygon 已转换为 path(宽度 0)")
✅ 使用说明
在 KLayout 中打开你的 GDS 或 OASIS 文件。
打开菜单:Macros(Window) > Macro Development
新建一个 "Python" 宏,复制粘贴上面的脚本。
点击 "Run" 执行脚本。
在图层 1/0 中,原来的 polygon 会被替换或复制为 width=0 的 path。
🔁 如果你 不想改变原图层 ,而是导入到新的图层
把这行:
python Copy code
shapes = top_cell.shapes(layer_index)
替换为:
python Copy code
target_layer_info = pya.LayerInfo(10, 0) # 例如导入图层 10/0
target_layer_index = layout.layer(target_layer_info)
shapes = top_cell.shapes(target_layer_index)
如果你对处理多个 cell、多层或只处理特定结构有需求,也欢迎继续提问,我可以帮你加上相关逻辑 ✅