How do I edit keymaps with Python?

Trying to build an eraser for Texture Paint mode.

• Holding LEFT_SHIFT should store the current blend mode then switch it to “Erase Alpha” (while it’s being held down. This part I have figured out. Note, it can’t be shift-left mouse because shift-left mouse must be mapped to allow for standard painting while shift is being held down. This is a much faster and better way of switching for this situation.)

• Then I need to add Shift-Left Mouse to a “paint.image_paint” keymap so that holding Shift from the first command won’t stop the brush from painting.

• Finally, I need Shift-Left Mouse Release to restore the original blend mode.

From the example provided by Blender.org I’ve got this much figured out:


import bpy

class shiftEraser(bpy.types.Operator):
    bl_idname = "paint.shift_eraser"
    bl_label = "Shift Eraser"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.context.tool_settings.image_paint.brush.blend = 'ERASE_ALPHA'
        return {'FINISHED'}
   

#Create Keymaps list
addon_keymaps = []

def register():
    bpy.utils.register_class(shiftEraser)

    # handle the keymap
    wm = bpy.context.window_manager
    km = wm.keyconfigs.addon.keymaps.new(name='Image Paint', space_type='EMPTY')
    kmi = km.keymap_items.new(shiftEraser.bl_idname, 'LEFT_SHIFT', 'PRESS')
    addon_keymaps.append(km)

def unregister():
    bpy.utils.unregister_class(shiftEraser)

    # handle the keymap
    wm = bpy.context.window_manager
    for km in addon_keymaps:
        wm.keyconfigs.addon.keymaps.remove(km)
    # clear the list
    del addon_keymaps[:]

if __name__ == "__main__":
    register()

So from this, I’ve gleamed how to add new keymaps for custom operators but how would I add a new command to an operator that already exists i.e. paint.image_paint? I should point out I’ve already tested the functionality, works great, just need to know how to map it in via python instead of in the user preferences by hand.

The line where you have shiftEraser.bl_idname:

kmi = km.keymap_items.new(shiftEraser.bl_idname, 'LEFT_SHIFT', 'PRESS')

shiftEraser’s bl_idname is a string so you just pass a different string. i.e. for bpy.ops.something.something you would put “something.something” ( leave off the bpy.ops. part for the bl_idname )

how would I add a new command to an operator that already exists i.e. paint.image_paint?

Not sure what you mean? A new mode / property?

If you successfully set this all up via the UI, it should be easy to do the same with python. Just add two more keymap items like the one you already did.

Dude, you saved my bacon. I probably should have noticed that, but yay I am at the end of my first major Blender coding campaign. Thanks a ton!