Need help for a script of saving screenshot for many times

Hi, I am working on this red slice

The range is from -500mm to 500mm, and all I know is I can save it by clicking Annotation Screenshot, and choosing Red Slice View
It would be great if someone could provide a Python script to save the Red Slice every 10 mm as png in an absolute directory, for example, C:\Users\jp1234\Documents

Thank you!

This snippet from the repository should get you started …

Thanks, I created this one, and copied it to the Python Console, but nothing shows up

layoutName = "Red"
imagePathPattern = "C:/Users/jp1234/Documents/red_slice-%03d.png"
startOffset = -10
endOffset = 50
stepSize = 10

widget =
view = widget.sliceView()
logic = widget.sliceLogic()
bounds = [0,]*6

currentOffset = startOffset
stepCount = 0

while currentOffset <= endOffset:
    image = view.grab().toImage() % stepCount)
    currentOffset += stepSize
    stepCount += 1

then I tried the example, but [Qt] QPixmap::grabWidget is deprecated, use QWidget::grab() instead

so I use this

img = qt.QWidget.grab(slicer.util.mainWindow()).toImage()"C:/Users/jp1234/Documents/red_slice-%03d.png")

Still nothing shows up

ChatGPT is here to help:-)

The last code iteration works:

import os
import slicer

# Define the directory to save images
output_directory = "C:/Users/yourname/Documents/SlicerOutput"
if not os.path.exists(output_directory):

# Define the range and step size
start = -500
end = 500
step = 10

# Get the Red Slice widget
red_logic ="Red").sliceLogic()

# Function to take and save screenshot
def saveScreenshot(sliceLogic, filename):
    layoutManager =
    sliceNode = sliceLogic.GetSliceNode()
    sliceView = layoutManager.sliceWidget(sliceNode.GetLayoutName()).sliceView()
    w2i = vtk.vtkWindowToImageFilter()
    writer = vtk.vtkPNGWriter()

# Iterate over the range and save images
for position in range(start, end + 1, step):
    # Set the slice offset

    # Define the file path
    filename = f"Red_Slice_{position}mm.png"
    filepath = os.path.join(output_directory, filename)

    # Save the screenshot
    saveScreenshot(red_logic, filepath)

    # Optional: Print the file path to confirm saving
    print("Saved:", filepath)

print("All slices saved successfully.")