You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Blender Python的enum实现带图标的工具激活菜单?

Blender Python 自定义图标工具菜单实现方案

完整可运行代码

import bpy

# 定义工具选项枚举
class VIEW3D_MT_CustomToolMenu(bpy.types.PropertyGroup):
    tool_options: bpy.props.EnumProperty(
        items=[
            # (标识符, 显示名称, 描述, 图标, 索引)
            ("TOOL_SELECT", "", "选择工具", "SELECT_SET", 0),
            ("TOOL_MOVE", "", "移动工具", "VIEW_TRANSLATE", 1),
            ("TOOL_ROTATE", "", "旋转工具", "VIEW_ROTATE", 2),
            ("TOOL_SCALE", "", "缩放工具", "VIEW_ZOOM", 3),
            ("TOOL_EXTRUDE", "", "挤出工具", "MOD_EXTRUDE", 4),
        ],
        name="自定义工具菜单",
        update=lambda self, context: update_tool_selection(self, context)
    )

# 枚举切换时触发工具激活逻辑(功能代码核心位置)
def update_tool_selection(self, context):
    # 映射枚举项到Blender工具ID
    tool_map = {
        "TOOL_SELECT": "builtin.select_box",
        "TOOL_MOVE": "builtin.move",
        "TOOL_ROTATE": "builtin.rotate",
        "TOOL_SCALE": "builtin.scale",
        "TOOL_EXTRUDE": "builtin.extrude_region"
    }
    selected_tool = self.tool_options
    if selected_tool in tool_map:
        bpy.ops.wm.tool_set_by_id(name=tool_map[selected_tool])

# 创建3D视口侧边栏面板(模仿视口着色菜单样式)
class VIEW3D_PT_CustomToolPanel(bpy.types.Panel):
    bl_label = "自定义工具"
    bl_idname = "VIEW3D_PT_custom_tool_panel"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = "视图"  # 与视口着色菜单同分类,可自定义名称

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        
        # 绘制仅显示图标的横向按钮组
        row = layout.row(align=True)
        row.prop_enum(scene.custom_tool_menu, "tool_options", "TOOL_SELECT")
        row.prop_enum(scene.custom_tool_menu, "tool_options", "TOOL_MOVE")
        row.prop_enum(scene.custom_tool_menu, "tool_options", "TOOL_ROTATE")
        row.prop_enum(scene.custom_tool_menu, "tool_options", "TOOL_SCALE")
        row.prop_enum(scene.custom_tool_menu, "tool_options", "TOOL_EXTRUDE")

# 注册/注销流程
def register():
    bpy.utils.register_class(VIEW3D_MT_CustomToolMenu)
    bpy.utils.register_class(VIEW3D_PT_CustomToolPanel)
    bpy.types.Scene.custom_tool_menu = bpy.props.PointerProperty(type=VIEW3D_MT_CustomToolMenu)

def unregister():
    bpy.utils.unregister_class(VIEW3D_MT_CustomToolMenu)
    bpy.utils.unregister_class(VIEW3D_PT_CustomToolPanel)
    del bpy.types.Scene.custom_tool_menu

if __name__ == "__main__":
    register()

关键细节说明

  • 功能代码位置:工具激活逻辑写在update_tool_selection函数中,通过EnumProperty的update参数绑定,每次点击图标切换枚举值时自动触发。
  • 仅显示图标设置:枚举项的显示名称留空字符串,绘制时就只会渲染图标;用row(align=True)让按钮横向对齐,和视口着色菜单样式一致。
  • 工具ID验证:如果工具无法激活,去Blender偏好设置→快捷键面板,搜索对应工具查看正确的ID名称,替换tool_map中的值即可。
  • 扩展自定义工具:新增工具只需在枚举items里加新项,同时在tool_map中绑定自定义工具的ID。

内容的提问来源于stack exchange,提问作者Pow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:39:18