1

I want my object to switch between Edit mode and Object mode every one second, So I wrote this code:

import bpy

def tester(): obj = bpy.context.scene.objects['Cube'] if (bpy.context.mode == 'OBJECT'): bpy.ops.object.mode_set(mode='EDIT', toggle=False)
else:
bpy.ops.object.mode_set(mode='OBJECT', toggle=False) return 1

bpy.app.timers.register(tester)

but I got this error message :

RuntimeError: Operator bpy.ops.object.mode_set.poll() failed, context is incorrect
Harry McKenzie
  • 10,995
  • 8
  • 23
  • 51
AlecDev
  • 97
  • 5

1 Answers1

3

Try the following script for Blender 3.2 and above. You can read more about context here poll() failed, context incorrect? - Example: bpy.ops.view3d.background_image_add()

import bpy

area_type = 'VIEW_3D' # change this to use the correct Area Type context you want to process in areas = [area for area in bpy.context.window.screen.areas if area.type == area_type]

if len(areas) <= 0: raise Exception(f"Make sure an Area of type {area_type} is open or visible in your screen!")

def mode_set(mode, toggle): with bpy.context.temp_override( window=bpy.context.window, area=areas[0], regions=[region for region in areas[0].regions if region.type == 'WINDOW'][0], screen=bpy.context.window.screen ):

    bpy.ops.object.mode_set(mode=mode, toggle=toggle)


def tester(): obj = bpy.context.scene.objects['Cube'] if (bpy.context.mode == 'OBJECT'): mode_set(mode='EDIT', toggle=False) else:
mode_set(mode='OBJECT', toggle=False) return 1

bpy.app.timers.register(tester)

Harry McKenzie
  • 10,995
  • 8
  • 23
  • 51