Python Assistant Prompts: Selection By Element Type


 

Prompt Used:

Can you write a script which selects all elements of specific type 
(e.g., all Text Elements or all Cell Elements) in the active model?

 

 

Python Assistant Generated Code:

from MSPyBentley import *
from MSPyECObjects import *
from MSPyBentleyGeom import *
from MSPyDgnPlatform import *
from MSPyDgnView import *
from MSPyMstnPlatform import *

import tkinter as tk
from tkinter import simpledialog, messagebox

def selectElementsbyType(inputElementType):
    """
    Select elements of a specific type from the active model.

    :param inputElementType: The type of elements to select (int).
    """
    ACTIVEMODEL = ISessionMgr.ActiveDgnModelRef
    dgnModel = ACTIVEMODEL.GetDgnModel()
    graphicalElements = dgnModel.GetGraphicElements()
    selSetManager = SelectionSetManager.GetManager()
    selSetManager.EmptyAll()  # Clear previous selection

    count = 0
    for perElementRef in graphicalElements:
        eh = ElementHandle(perElementRef)
        msElement = EditElementHandle(perElementRef, dgnModel).GetElement()
        isGraphics = msElement.ehdr.isGraphics
        isInvisible = msElement.hdr.dhdr.props.b.invisible
        if isGraphics and not isInvisible:
            eleType = eh.GetElementType()
            if eleType == inputElementType:
                selSetManager.AddElement(perElementRef, dgnModel)
                count += 1

    agenda = ElementAgenda()
    selSetManager.BuildAgenda(agenda)
    messagebox.showinfo("Selection Complete", f"Selected {count} elements of type {inputElementType}.")

# --- UI to prompt for element type ---
def prompt_and_run():
    root = tk.Tk()
    root.withdraw()
    type_str = simpledialog.askstring(
"Element Type", "Enter element type number (e.g., 17 for Text, 2 for Cell):") if type_str is None: return try: inputElementType = int(type_str) except ValueError: messagebox.showerror("Error", "Invalid element type number.") return selectElementsbyType(inputElementType) def main(): prompt_and_run() if __name__ == "__main__": main()

 

 

Python: Documentation | API Presentations | FAQs | GitHub | Samples | Wikis | Blogs