FreeCAD Python Script to Create a 3D Box

Automating 3D modeling in FreeCAD via its built-in Python console allows users to generate parametric geometry programmatically without manual GUI interaction. This guide demonstrates how to set up an active document, instantiate a standard 3D solid box, define its dimensions and position, and recompute the scene using FreeCAD's core scripting modules.

Accessing the Python Environment

FreeCAD features an integrated Python interpreter. You can run code directly inside the application:

  1. Open FreeCAD.
  2. Ensure the Python console is visible by navigating to View > Panels > Python console.
  3. Alternatively, create a reusable macro by going to Macro > Macros..., clicking Create, naming the file (e.g., CreateBox.FCMacro), and pasting the code into the editor.

The Python Script

The following script checks for an open document, creates one if none exists, defines a new solid box, sets its length, width, and height, and refreshes the viewport.

import FreeCAD as App
import Part

# 1. Ensure an active document exists
doc = App.ActiveDocument
if doc is None:
    doc = App.newDocument("ParametricBoxModel")

# 2. Add a parametric Box object to the document
box = doc.addObject("Part::Box", "CustomBox")

# 3. Define the dimensions (values in millimeters)
box.Length = 50.0
box.Width = 30.0
box.Height = 20.0

# 4. Set the position in 3D space (X, Y, Z coordinates)
box.Placement.Base = App.Vector(10.0, 10.0, 0.0)

# 5. Recompute the document to update the 3D view
doc.recompute()

How the Code Works

  • import FreeCAD as App and import Part: Imports the base application module to manage the workspace and the Part module to access standard solid geometries.
  • doc.addObject("Part::Box", "CustomBox"): Creates a parametric cube/box primitive in the scene tree labeled "CustomBox".
  • box.Length, box.Width, box.Height: Sets the geometric bounds of the box along the X, Y, and Z axes, measured in FreeCAD's default unit (millimeters).
  • box.Placement.Base: Moves the origin corner of the box using a 3D vector (App.Vector(x, y, z)).
  • doc.recompute(): Forces FreeCAD to evaluate the dependency tree and render the generated geometry inside the active 3D view.