Skip to content

Creating Custom Nodes

Description

This introductory tutorial will show you how you can begin to create your own ComfyUI custom nodes.

We will build a basic calculator, which will demonstrate,

  • naming your custom node,
  • using various inputs such as string, float and a dropdown,
  • calling a function,
  • utilize output type matching to improve node output suggestions.

This is a free introductory tutorial on a very specialized subject. If you want to know more, then consider becoming a member of my SBCODE YouTube channel and I can continue to schedule and build more videos about these more specialized subjects.

Create the Custom Node

  1. In your ComfyUI/custom_nodes folder, create a new folder named ComfyUI-Calculator.

  2. Create a new file named __init__.py and copy/paste this code below, into it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class CalculatorNode:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "number1": ("FLOAT", {"default": 0.0}),
                "number2": ("FLOAT", {"default": 0.0}),
                "operation": ("STRING", ),
                #"operation": (["+", "-", "*", "/", "%"], ),
            }
        }

    RETURN_TYPES = ("STRING",)
    #RETURN_TYPES = ("*",)
    FUNCTION = "calculate"
    CATEGORY = "SBCODE"

    def calculate(self, number1, number2, operation):
        try:
            if operation == "+":
                result = number1 + number2
            elif operation == "-":
                result = number1 - number2
            elif operation == "*":
                result = number1 * number2
            elif operation == "/":
                if number2 == 0:
                    return ("Error: Division by zero",)
                result = number1 / number2
            elif operation == "%":
                result = number1 % number2
            else:
                return ("Error: Unknown operation",)

            return (f"Result: {result}",)
        except Exception as e:
            return (f"Error: {str(e)}",)


NODE_CLASS_MAPPINGS = {
    "CalculatorNode": CalculatorNode
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "CalculatorNode": "Basic Calculator"
}