Note that you could also use something like:
bpy.ops.wm.context_set_id(data_path=“scene.objects.active”, value=“Cube”)
and its layout counterpart:
props = layout.operator(“wm.context_set_id”)
props.data_path = “scene.objects.active”
props.value = “Cube”
But that will change the active state only. What you usually want is to change the selection state as well - which could be solved by a custom operator:
import bpy
def main(context):
for ob in context.scene.objects:
print(ob)
class SimpleOperator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.simple_operator"
bl_label = "Simple Object Operator"
def execute(self, context):
ob = bpy.data.objects.get("Cube")
if ob is not None:
ob.select = True
context.scene.objects.active = ob
return {'FINISHED'}
def register():
bpy.utils.register_class(SimpleOperator)
def unregister():
bpy.utils.unregister_class(SimpleOperator)
if __name__ == "__main__":
register()
# test call
bpy.ops.object.simple_operator()
It will not clear a previous selection, but would be trivial to add.