5. Interactive Line Drawing in AutoCAD with Python

Do not delve into computer theory

Not a programming expert

Best applicable

Task: Create a line in AutoCAD by selecting two points, place the line on the LINE layer, and set it to red.Method 1:

import win32com.client
import pythoncom

# Create a line by selecting two points and setting layer and color
def create_line_by_selection():
    try:
        # Connect to AutoCAD
        acad = win32com.client.GetActiveObject("AutoCAD.Application")
        doc = acad.ActiveDocument
        model_space = doc.ModelSpace

        # Select the first point
        print("Please select the start point...")
        start_result = doc.Utility.GetPoint()
        start_point = win32com.client.VARIANT(
            pythoncom.VT_ARRAY | pythoncom.VT_R8,
            (start_result[0], start_result[1], start_result[2])
        )
        print(f"   Start Point: ({start_result[0]:.2f}, {start_result[1]:.2f}, {start_result[2]:.2f})")

        # Select the second point
        print("Please select the end point...")
        end_result = doc.Utility.GetPoint()
        end_point = win32com.client.VARIANT(
            pythoncom.VT_ARRAY | pythoncom.VT_R8,
            (end_result[0], end_result[1], end_result[2])
        )
        print(f"   End Point: ({end_result[0]:.2f}, {end_result[1]:.2f}, {end_result[2]:.2f})")

        # Create or get the LINE layer
        layers = doc.Layers
        try:
            # Try to get the existing LINE layer
            line_layer = layers.Item("LINE")
            print("Using existing LINE layer")
        except:
            # If it does not exist, create a new layer
            line_layer = layers.Add("LINE")
            line_layer.Color = 1  # Red
            print("Created new LINE layer (red)")

        # Create the line
        new_line = model_space.AddLine(start_point, end_point)

        # Set line properties
        new_line.Layer = "LINE"  # Set to LINE layer
        new_line.Color = 1       # Set to red

        # Calculate line length
        dx = end_result[0] - start_result[0]
        dy = end_result[1] - start_result[1]
        length = (dx**2 + dy**2)**0.5
        print("Line created successfully!")
        print(f"Length: {length:.2f}")
        print(f"Layer: LINE (red)")

        # Highlight the newly created line
        new_line.Highlight(True)
        return new_line
    except Exception as e:
        print(f"Failed to create line: {e}")
        return None

# Run create_line_by_selection()

Method 2:

import win32com.client
import pythoncom

# Line creation with options
def create_line_with_advanced_options():
    try:
        acad = win32com.client.GetActiveObject("AutoCAD.Application")
        doc = acad.ActiveDocument
        layers = doc.Layers
        print("Advanced line creation...")

        # Ensure LINE layer exists and set properties
        try:
            line_layer = layers.Item("LINE")
        except:
            line_layer = layers.Add("LINE")
            line_layer.Color = 1  # Red
            line_layer.Lineweight = 25  # 0.25mm line width
            print("Created LINE layer (red, 0.25mm line width)")

        # Select start and end points
        print("Please select the start point...")
        start_point_obj = doc.Utility.GetPoint()
        start_var = win32com.client.VARIANT(
            pythoncom.VT_ARRAY | pythoncom.VT_R8,
            (start_point_obj[0], start_point_obj[1], start_point_obj[2])
        )

        end_point_obj = doc.Utility.GetPoint(start_var, "Please select the end point...")
        end_var = win32com.client.VARIANT(
            pythoncom.VT_ARRAY | pythoncom.VT_R8,
            (end_point_obj[0], end_point_obj[1], end_point_obj[2])
        )

        # Create the line
        line = doc.ModelSpace.AddLine(start_var, end_var)

        # Set line properties
        line.Layer = "LINE"
        line.Color = 1

        # Display details
        print("Line created successfully!")
        print(f"Start Point: ({start_point_obj[0]:.2f}, {start_point_obj[1]:.2f})")
        print(f"End Point: ({end_point_obj[0]:.2f}, {end_point_obj[1]:.2f})")
        print(f"Length: {line.Length:.2f}")
        print(f"Properties: LINE layer, red")
        return line
    except Exception as e:
        print(f"Failed: {e}")
        return None

# Run create_line_with_advanced_options()

Method 3:

# Try using Pyautocad
from pyautocad import Autocad, APoint

def create_line_correct():
    try:
        acad = Autocad(create_if_not_exists=True)
        doc = acad.doc
        print("Interactive line drawing program")
        print("=" * 20)

        # Select start point - using doc.Utility.GetPoint()
        print("Please select the start point...")
        start_result = doc.Utility.GetPoint()
        start_point = APoint(start_result[0], start_result[1])
        print(f"Start Point: ({start_point.x:.2f}, {start_point.y:.2f})")

        # Select end point
        print("Please select the end point...")
        end_result = doc.Utility.GetPoint()
        end_point = APoint(end_result[0], end_result[1])
        print(f"End Point: ({end_point.x:.2f}, {end_point.y:.2f})")

        # Draw line
        line = acad.model.AddLine(start_point, end_point)
        line.Color = 1  # Red
        print("Line created successfully!")
        print(f"Length: {line.Length:.2f}")
        return line
    except Exception as e:
        print(f"Error: {e}")
        return None

# Run create_line_correct()

Summary

  • GetPoint: Try the prompt parameters of GetPoint.

  • pyautocad: Understand the APoint’s VARIANT.

A vast field, a day’s harvest; a grand house, a night’s rest.

——“Expanded Wisdom”

Leave a Comment