Search code examples
pythonmayapymelmaya-api

Maya 2022 crashes while i run a python script


I am trying to create a menu, a submenu and an optionBox which lets the submenu item to create and remove itself from main menu. when I continuously try to add and remove the item from the main menu maya crashes with the message

Fatal Error. Attempting to save in "{temp location}".ma

it seems the name keeps recreating itself and the app crashes or something similar is happening.

import pymel.core as pm

MainMayaWindow = pm.language.melGlobals['gMainWindow']
c=None

customMenu = pm.menu('Custom Menu', parent=MainMayaWindow, tearOff=True)
a=pm.menuItem(label="menu item 1'", parent=customMenu, subMenu=True)
b=pm.menuItem(label="click me", parent=a)
pm.menuItem(command="newItem()", parent=a, optionBox=True)

def newItem():
  global c
  if not c:
    c=pm.menuItem(label="click me", parent=customMenu)
    pm.menuItem(command="removeItem()", parent=customMenu, optionBox=True)
  else:    
    print("already exist")

def removeItem():
  global b,c
  print("removed item")
  pm.deleteUI(c, control=True)
  c=None

I used tearoff menu to test as it was quicker/easier to test with continuos clicks. i also tried to change the label as unique which didnt work either. i tried this with maya.cmds as well.


Solution

  • Removing the same UI element which contains the command is not a recommended procedure and can produce the effect you see. You should try to think about your program logic to avoid this process. You can try to use an evalDeferred() to remove the item, but even if this works, it's a suboptimal solution. And I heavily recommend to avoid global variables and use a python class to create the UI.