Community
AutoCAD Forum
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Python add attributes to block

3 REPLIES 3
SOLVED
Reply
Message 1 of 4
vabb
1532 Views, 3 Replies

Python add attributes to block

Hello everyone, I have an autocad file with several already existing blocks. I would like to add two new attributes to all the blocks of a certain Layer. Now I am at an early stage and I am testing my code with a file with only one block but I am not able to access the Block definition for correctly caling the AddAttribute function.

 

 

from pyautocad import aDouble 
import win32com.client 
acad = win32com.client.Dispatch("AutoCAD.Application") 
doc = acad.ActiveDocument 
# Document object 
blocks= acad.ActiveDocument.Blocks
res = blocks.AddAttribute(50, 0, "test", aDouble(200, 100, 0), "TEST", "TEST TEXT")

 

 

 

Tags (2)
3 REPLIES 3
Message 2 of 4
jayhar
in reply to: vabb

To add attributes to all blocks on a certain layer in an AutoCAD file using Python and the `pyautocad` library, you can follow these steps:

 

1. Import the required modules:
```python
from pyautocad import aDouble
import win32com.client
```

 

2. Connect to the AutoCAD application and open the active document:
```python
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument
```

 

3. Get the blocks collection and iterate over all the blocks:
```python
blocks = doc.Blocks
for block in blocks:
# Check if the block is on the desired layer
if block.Layer == "YourLayerName":
# Add the attributes to the block
res = block.AddAttribute(
50, # Tag value
0, # Invisible attribute flag
"test", # Prompt
aDouble(200, 100, 0), # Insertion point
"TEST", # Tag
"TEST TEXT" # Default value
)
```

 

Make sure to replace `"YourLayerName"` with the name of the layer you want to target. This code will add the attributes to all the blocks on that layer. You can modify the attribute parameters as per your requirements.

Note: The code assumes that you have already installed the `pyautocad` library and have a working installation of AutoCAD.

 

Please Subscribe YouTube Channel
https://www.youtube.com/channel/UCclj8v9vHQiFa8_DriuAk3w

Please Mark the Post or Posts as Solution(s) to help others find the answer quickly.
Tags (1)
Message 3 of 4
vabb
in reply to: vabb

Thank you.

Message 4 of 4
vabb
in reply to: jayhar

@jayharwhy I cannot run the same code with pyautocad? Everything works except the Layer research. How can I check the layer with pyautocad?

If that is not possible, how can I just shut down the other layers from the model Space and work only with layers I am interested too? Luckily I do not have the same block in more layers

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Forma Design Contest


AutoCAD Beta