6
$\begingroup$

I am attempting to make a custom menu in Python that is context sensitive. Such that it's contents vary depending on which mode your currently in (e.g. Edit mode or Object mode).

However, when using an if and elif statement it doesn't work, and simply doesn't show those parts of the menu.

What am I doing wrong?

class QuickObjectOptions(bpy.types.Menu):
bl_idname = "object.display_options"
bl_label = "Quick Object Options"

mode = bpy.context.object.mode

def draw(self, context):
    layout = self.layout

    if mode == 'OBJECT':
        layout.operator("object.shade_smooth", icon='SOLID')
        layout.operator("object.shade_flat", icon='MESH_UVSPHERE')
    elif mode == 'EDIT':
        layout.operator("mesh.faces_shade_smooth", icon='SOLID')
        layout.operator("mesh.faces_shade_flat", icon='MESH_UVSPHERE')

Note: I've only pasted the relavant parts of the script above to keep it simple. The "import bpy" and register functions are definitely there ;)

$\endgroup$

1 Answer 1

8
$\begingroup$

Answering my own question via vitos1k on IRC.

In order for the the if/elif statements to recognize the variable it needs to be placed inside the draw function.

Correct code:

class QuickObjectOptions(bpy.types.Menu):
bl_idname = "object.display_options"
bl_label = "Quick Object Options"

def draw(self, context):

    mode = context.object.mode
    layout = self.layout

    if mode == 'OBJECT':
        layout.operator("object.shade_smooth", icon='SOLID')
        layout.operator("object.shade_flat", icon='MESH_UVSPHERE')
    elif mode == 'EDIT':
        layout.operator("mesh.faces_shade_smooth", icon='SOLID')
        layout.operator("mesh.faces_shade_flat", icon='MESH_UVSPHERE')
$\endgroup$
4
  • 1
    $\begingroup$ Declaring a variable outside a function makes it a global variable. Therefore mode is initialized when the object is created but not updated when the value of bpy.context.object.mode changes. $\endgroup$
    – stacker
    Commented May 26, 2013 at 6:08
  • $\begingroup$ Ah that makes more sense. Thanks for the extra info @stacker $\endgroup$ Commented May 26, 2013 at 15:07
  • 1
    $\begingroup$ Note that this is even disallowed for addons, bpy.context is restricted to accessing only a few members. In this case its just annoying but if you store types that wrap internal data - you can cause crashes on further access if that data happens to be removed. $\endgroup$
    – ideasman42
    Commented May 27, 2013 at 8:45
  • 1
    $\begingroup$ On that line mode = bpy.context.object.mode you can drop the bpy, because you already have context. so mode = context.object.mode $\endgroup$
    – zeffii
    Commented May 27, 2013 at 14:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .