Calling functions by pressing buttons in Blender custom UI

Button click in basically connected with the operator calling in Blender user interface. However, some times actions, that need to be performed when a button is pressed, are quite simple and do not require a separate operator for them. And it makes no sense to fill a registered operators stack with a multitude of specific operators designed to perform one highly specialized function. It would be much more convenient to associate a button press with a separate function call but the Blender API allows to associate buttons only with an operator call.

To solve the problem of creating a separate operator for each button we can use the fact that the operator can be called with the input parameters.

Let’s create a simple operator class:

and define here some separate functions:

  • clear_scene – for removing all the meshes from the scene
  • add_cube – for adding a cube
  • add_sphere – for adding a sphere

Now the main feature – let’s add an input parameter of EnumProperty type for our operator.

According to this parameter value, we will call the desired function. The first item in the list is a text identifier, which will be used as a parameter value.

Modify the operator’s “execute” method to call the desired function depending on the “action” value:

Now, if the operator is called with the “CLEAR” parameter, its “clear_scene” function will be executed, with the “ADD_CUBE” parameter – the “add_cube” function will be executed and so on.

The complete operator code looks the following:

Let’s create a tab in the N-panel with our custom sub-panel to place the buttons:

In the “draw” method of our panel we defined three buttons: “Clear scene”, “Add cube” and “Add sphere”. And assigned each of them a call of our operator, but for each – with its own “action”: “CLEAR”, “ADD_CUBE “and” ADD_SPHERE”. As a result, when the button is pressed, the same operator is called, but with a different parameter to call different functions in accordance with this parameter value.

The final code:

Now we got a mechanism for calling various functions by pressing buttons without creating and registering a set of operators for each of the buttons.