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

ComfyUI自定义节点开发:如何实现主选项联动动态更新子选项?

ComfyUI自定义节点实现动态切换输入项的解决方案

问题分析

你尝试在INPUT_TYPES中直接写条件判断生成输入项的思路不可行——INPUT_TYPES是类方法,在节点加载时就会执行并返回静态字典,无法随用户选择的mode实时更新输入项。

解决方案

需要结合后端Python逻辑接收所有可能的输入,再通过前端JavaScript控制输入框的显示/隐藏,实现动态切换效果。

1. 后端Python节点代码

将所有可能的输入项声明在required中,在process方法里根据mode选择处理对应的输入:

class DynamicInputNode:
    @classmethod
    def INPUT_TYPES(s):
        return {
            "required": {
                "mode": (["text", "file"],),
                "text_content": ("STRING", {
                    "multiline": False,
                    "default": "Text",
                }),
                "file_path": ("STRING", {
                    "multiline": False,
                    "default": "/",
                })
            },
        }
    
    RETURN_TYPES = ("STRING",)
    FUNCTION = "process"
    CATEGORY = "Custom Nodes"

    def process(self, mode, text_content, file_path):
        if mode == "text":
            # 此处可添加文本处理逻辑
            return (text_content,)
        else:
            # 此处可添加文件读取逻辑,示例返回路径
            # with open(file_path, 'r', encoding='utf-8') as f:
            #     content = f.read()
            # return (content,)
            return (file_path,)

将代码保存为dynamic_input_node.py,放入ComfyUI的custom_nodes目录。

2. 前端JavaScript控制代码

通过JS监听mode选项变化,动态切换输入框的显示状态:

document.addEventListener('DOMContentLoaded', () => {
    const targetNodeType = "DynamicInputNode";

    // 节点添加到画布时初始化监听
    api.addEventListener('nodeAdded', (event) => {
        const node = event.detail.node;
        if (node.type !== targetNodeType) return;

        // 初始化显示状态
        toggleInputWidgets(node);
        // 监听mode下拉框变化
        const modeWidget = node.widgets.find(w => w.name === "mode");
        modeWidget.element.addEventListener('change', () => toggleInputWidgets(node));
    });

    // 切换输入框显示/隐藏
    function toggleInputWidgets(node) {
        const selectedMode = node.widgets.find(w => w.name === "mode").value;
        const textWidget = node.widgets.find(w => w.name === "text_content").parentElement;
        const fileWidget = node.widgets.find(w => w.name === "file_path").parentElement;

        textWidget.style.display = selectedMode === "text" ? "block" : "none";
        fileWidget.style.display = selectedMode === "file" ? "block" : "none";
    }
});

将代码保存为dynamic_input_node.js,放入ComfyUI的web/extensions/custom_nodes目录(若无该目录则新建)。

3. 测试步骤

  1. 重启ComfyUI
  2. 在节点菜单的Custom Nodes分类中找到DynamicInputNode
  3. 切换mode选项,即可看到对应的输入框动态显示/隐藏

内容的提问来源于stack exchange,提问作者NAI-00 Lab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:16:00