Локальные переменные и глобальные переменные, имя 'EXAMPLE' не определено - PullRequest
2 голосов
/ 14 мая 2019

Я создаю настраиваемое плавающее окно, в котором у меня могут быть кнопки наподобие полки, которые вызывают и запускают сценарии для меня.Очень полезно для таких модельных художников, как я, которые не занимаются написанием сценариев!: P Я надеюсь решить эту проблему без необходимости слишком много изменять Script_B, но мы посмотрим, что нужно сделать!: D

Итак, у меня есть два сценария, Script_A и Script_B.Скрипт B сохраняется как «my_custom_script_name.py».Я пытаюсь запустить его с помощью Script_A, но переменные никогда не определяются должным образом.

Когда я запускаю Script_A с Script_B, сохраненным в нужном месте, пользовательский интерфейс даже не загружается, потому что он выдает ошибки наопределена первая переменная.

# Error: NameError: file C:/Users/polyshifter/Documents/maya/2019/prefs/scripts\my_custom_script_name.py line 2: global name 'mc' is not defined # 

Итак, мы еще не дошли до других переменных, и она сломана.

SCRIPT A

import maya.cmds as mc
import maya.mel as mel

# Create a custom floating window with 
if mc.window('ToolsWindow', q=True, exists=True):
    mc.deleteUI('ToolsWindow')
if mc.workspaceControl('ToolsWorkspaceControl', q=True, exists=True):
    mc.deleteUI('ToolsWorkspaceControl')
mc.window('ToolsWindow')
mc.tabLayout('ToolsTabs')

###IMPORT PANEL###

tabMenu = mc.columnLayout("Menu", adj=True)
separator_long = mc.separator(
                         height=10,
                         style='in')


mc.button(label="MyCustomScript", command = "my_custom_script_com()")

mc.setParent('..')
mc.showWindow()

#### My custom script ####
def my_custom_script_com(*args):
    import my_custom_script_name
    my_custom_script_name.run_my_custom_script_ui()

СЦЕНАРИЙ B

def run_my_custom_script_ui():
    import maya.cmds as mc
    if mc.window('my_script_ui', q=True, exists=True):
        mc.deleteUI('my_script_ui')
    else:
        mc.window('my_script_ui')

    mc.columnLayout("Menu", adj=True)

    mc.button(label="Please_print", command = "please_print()")

    mc.setParent('..')
    mc.showWindow()
    def please_print():
        print "OMG IT'S FINALLY WORKING!! YAY!!"

Я попытался поместить Script_B в Script_A в самом конце сценария, например:

def my_custom_script_com(*args):
    import maya.cmds as mc
    if mc.window('my_script_ui', q=True, exists=True):
        mc.deleteUI('my_script_ui')
    else:
        mc.window('my_script_ui')

    mc.columnLayout("Menu", adj=True)

    mc.button(label="Please_print", command = "please_print()")

    mc.setParent('..')
    mc.showWindow()
    def please_print():
        print "OMG IT'S FINALLY WORKING!! YAY!!"

В котором первый пользовательский интерфейс загружается, а затем второй, и я вижу свою кнопку, но когда я нажимаю на нее, я получаю:

# Error: NameError: file <maya console> line 1: name 'please_print' is not defined #

Я извиняюсь, если слишком много ненужного кода иливсе, что я пытался обрезать до костей как можно больше.Это мой первый вопрос!

Любая помощь в правильной работе этих переменных была бы потрясающей!<3 Заранее спасибо! </p>

Большое спасибо за помощь всем!Theodox смог решить эту проблему безупречно!

Однако… проблема сохраняется в моем не упрощенном сценарии!

У меня есть сценарий от этого художника, Леонардо Лецци."https://www.linkedin.com/pulse/super-bool-tool-python-leonardo-iezzi/" Когда я беру его скрипт и пытаюсь внедрить его в мой, он вызывает ошибки. Сначала не определяется pma, а затем ни одно из его определений.

У меня естьпопытался создать свой пользовательский интерфейс (учебный и основной) и определить их в команды, но это также не сработало для меня. Причина в том, что (из того, что я узнал сегодня: D), майя неу меня больше нет функций после того, как Script_B (теперь логический скрипт) вызывается.

Единственный найденный мной метод - это поместить логический скрипт в мой основной, чтобы он соответствовал ему.определите его пользовательский интерфейс как команды, а затем перечислите эти 2 команды с помощью нажатия моей кнопки из ScriptA . И затем запустите его. Но ТО вернитесь и удалите определения в сценарии, а затем введитезатем снова запустите сценарий. Так что определения по-прежнему определены для запуска ранее, но теперь пользовательский интерфейс выполняется глобально ... Очевидно, это ломается, когда вы перезапускаете Maya, и я ПОЛНОСТЬЮ mвопрос о том, как сделать их определенными, но при этом я буду вызывать их (правда?), когда я нажимаю кнопку.

Это явно хак и глупый способ сделать это, но я неЯ не понимаю, как заставить "super bool tool" запускаться из моего скрипта, только используя super_bool_tool.py

Ниже приведено то, что у меня есть, но опять-таки, идея здесь NOT чтобы запустить это внутри моего скрипта пользовательского интерфейса.Я хочу вызвать скрипт python, чтобы он мог жить сам по себе.

import maya.cmds as mc
import maya.mel as mel
import pymel.all as pma

BOOLEANMODE_ADD = 1
BOOLEANMODE_SUBTRACT = 2
PRIMITIVE_CUBE = 0
PRIMITIVE_CYLINDER = 1
PRIMITIVE_SPHERE = 2
PRIMITIVE_CUSTOM = 3


def cleanUp ():
    pma.delete (constructionHistory=True)
    #pma.select ()
    pma.delete ("*_ctrl*")

def hider(option):
    if (option == 0):
        pma.hide ()
    elif (option == 1):
        pma.select ("*_ctrl*")
        pma.hide ()
    elif (option == 2):
        pma.select ("*_ctrl*")
        pma.showHidden ()
        pma.select (clear=True)

def fixMaterial():
    pma.hyperShade( assign="lambert1" )

def triangulate():
    pma.polyTriangulate()

def creator(primitives):
    selection = pma.ls(sl=True)
    for x in selection:

        if primitives == PRIMITIVE_CUBE:
            a = makeCube() #Create cube
        if primitives == PRIMITIVE_CYLINDER:
            a = makeCyl() #Create cyl 
        if primitives == PRIMITIVE_SPHERE:
            a = makeSphere() #Create sphere 
        if primitives == PRIMITIVE_CUSTOM:
            a = selection[1]  
            x = selection[0]
            pma.select (a)
        b = createController(a)
        meshConstrainer (b,a)
        operator(x,a) 
        pma.select (b)    


def operator(meshA, meshB):
   booleanmode = get_boolean_mode()
   pma.polyBoolOp( meshA, meshB, op=booleanmode, n="basemesh" )
   pma.hyperShade( assign="lambert1" )   #REMINDER: Need to be replaced with the actual assigned material and not with a lambert1 so for who is working with other materials can easyly keep using that


def get_boolean_mode():
    if pma.radioButton(addRadioB, query = True, select = True) :
        return BOOLEANMODE_ADD
    if pma.radioButton(subRadioB, query = True, select = True) :
        return BOOLEANMODE_SUBTRACT
    return None

def makeCube():
    cubeTransform = pma.polyCube(n="cubetobool", w=1, h=1, d=1, sx=1, sy=1, sz=1)[0]   
    return cubeTransform       

def makeCyl():
    cylTransform = pma.polyCylinder(n="cubetobool", r=1, h=2, sx=20)[0]   
    return cylTransform   

def makeSphere():
    sphereTransform = pma.polySphere(n="cubetobool", r=1, sx=20, sy=20, cuv=2)[0]   
    return sphereTransform    


def meshConstrainer(constrainer, constrained):   
    pma.scaleConstraint( constrainer, constrained, maintainOffset=True)
    pma.parentConstraint( constrainer, constrained, maintainOffset=True)


def createController(object):
    #object = pma.ls(sl=True) 
    pivotObj = pma.xform(object,query=True,t=True,worldSpace=True)
    edges = pma.filterExpand(pma.polyListComponentConversion(te=1),sm=32,ex=1) # convert edges to curve ancd create one object
    for edge in edges:
        vtx = pma.ls(pma.polyListComponentConversion(edge,fe=1,tv=1),fl=1)
        p1 = pma.pointPosition(vtx[0])
        p2 = pma.pointPosition(vtx[1])
        curves = pma.curve(n="line_ctrl_curve", d=1,p=(p1,p2))

    ctrl = pma.curve (n="bool_ctrl", d=1,ws=True, p=pivotObj)
    pma.xform (centerPivots=True)
    for curveEdge in pma.ls ("line_ctrl*"):
        pma.parent(curveEdge,ctrl, s=1, r=1)
        pma.rename(curveEdge, "shapeunused")


    transforms =  pma.ls(type='transform')
    deleteList = []
    for tran in transforms:
        if pma.nodeType(tran) == 'transform':
            children = pma.listRelatives(tran, c=True) 
            if children is None:
                #print '%s, has no childred' %(tran)
                deleteList.append(tran)

    if not deleteList:           
       pma.delete(deleteList)       
    return ctrl




#################TUTORIAL
def super_bool_tut():
    windowNameTut = "Tutorial"
    if (pma.window(windowNameTut , exists=True)):
        pma.deleteUI(windowNameTut) 
    windowTutorial = pma.window(windowNameTut, title = windowNameTut, width = 400, height = 300, backgroundColor = [0.2, 0.2, 0.2])
    pma.columnLayout( "testColumn", adjustableColumn = True)
    pma.text("intro", label = "This tool is a super tool to make booleans wrote by Leonardo Iezzi. To make it works correctly, you need to have your base mesh already even if just a cube. With your base mesh selected just press one of the three buttons on the windows to subtract or add those primitives. If you want to use a custom mesh for the operation: select your base mesh then the custom one (it's important to pick your base mesh first) and then press the 'Use custom mesh' button. After you have done, select your base mesh and press 'Clean Up.'",wordWrap= True, height = 100, backgroundColor = [0.2, 0.2, 0.2], align='left', parent = "testColumn")

     #pma.text("first", label = "1- Select always your main mesh first",wordWrap= True, height = 40, backgroundColor = [0.2, 0.2, 0.2], align='left', parent = "testColumn")
     #pma.text("secondo", label = "2- In case you want to use a custom mesh: Select first your main mesh then the mesh you want to add or subtract",wordWrap= True, height = 40, backgroundColor = [0.2, 0.2, 0.2], align='left', parent = "testColumn")
     #pma.text("third", label = "3- Everythong should works",wordWrap= True, height = 40, backgroundColor = [0.2, 0.2, 0.2], align='left', parent = "testColumn")



    pma.separator(parent = "testColumn", height=20)
    pma.button("goit", label = "Got it", width = 120, height = 40, backgroundColor = [0.5, 0.5, 0.5], parent = "testColumn", command = "pma.deleteUI(windowNameTut)")

    pma.showWindow()

################################################################################################UI################################################# 
# @@@@@@@    THIS IS POLYSHIFTER!! I HAVE ADDED THIS AS A FUNCTION INSTEAD OF LEAVING IT UNINDENTED
def super_bool_ui():
    windowName = "SuperBool"
    windowSize = (120, 200)
    if (pma.window(windowName , exists=True)):
        pma.deleteUI(windowName)
    window = pma.window( windowName, title= windowName, width = 120, height = 200 )
    pma.columnLayout( "mainColumn", adjustableColumn = True)

    ################################################################################################UI#################################################
    pma.gridLayout("nameGridLayout01", numberOfRowsColumns = (1,4), cellWidthHeight = (40,40), parent = "mainColumn")
    pma.symbolButton("nameButton1", image = "polyCube.png", width = 40, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout01", command = "creator(PRIMITIVE_CUBE)")
    pma.symbolButton("nameButton2", image = "polyCylinder.png", width = 40, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout01", command = "creator(PRIMITIVE_CYLINDER)")
    pma.symbolButton("nameButton3", image = "polySphere.png", width = 40, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout01", command = "creator(PRIMITIVE_SPHERE)")
    pma.columnLayout("columnLayoutName01", adjustableColumn = True, backgroundColor = [0.2, 0.2, 0.2])
    pma.radioCollection("collection10", parent = "columnLayoutName01")
    subRadioB = pma.radioButton("subRadio", select = True, label = "Sub")
    addRadioB = pma.radioButton("addRadio", label = "Add")
    pma.setParent( '..' )
    pma.setParent( '..' )
    ################################################################################################UI#################################################
    pma.separator(parent = "mainColumn", height=20)

    pma.button("customMeshB", label = "Use Custom Mesh", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "mainColumn", command = "creator(PRIMITIVE_CUSTOM)")

    pma.separator(parent = "mainColumn", height=20)
    ################################################################################################UI#################################################
    pma.gridLayout("nameGridLayout03", numberOfRowsColumns = (1,3), cellWidthHeight = (53,40), parent = "mainColumn")
    pma.button("hidSelB", label = "Hide Sel",  height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout03", command = "hider(0)")
    pma.button("hidAllB", label = "Hide All",  height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout03", command = "hider(1)")
    pma.button("showAll", label = "Show All",  height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout03", command = "hider(2)")

    pma.separator(parent = "mainColumn", height=20)

    pma.button("clean", label = "Clean Up", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "mainColumn", command = "cleanUp()")

    pma.separator(parent = "mainColumn", height=20)
    ################################################################################################UI#################################################
    ################################################################################################UI#################################################
    pma.gridLayout("nameGridLayout02", numberOfRowsColumns = (1,2), cellWidthHeight = (80,40), parent = "mainColumn")
    pma.button("triangB", label = "Triangulate", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout02", command = "triangulate()")
    pma.button("fixMatB", label = "FixMaterial", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = "nameGridLayout02", command = "fixMaterial()")
    ################################################################################################UI#################################################
    pma.showWindow()


###################################################################
##################                              ###################
##################    END OF SUPER BOOL TOOL    ###################
##################                              ###################
###################################################################
###################################################################
##################                              ###################
##################   BEGINNING OF MY UI SCRIPT  ###################
##################                              ###################
###################################################################

# Create a custom floating window with 
if mc.window('ToolsWindow', q=True, exists=True):
    mc.deleteUI('ToolsWindow')
if mc.workspaceControl('ToolsWorkspaceControl', q=True, exists=True):
    mc.deleteUI('ToolsWorkspaceControl')
mc.window('ToolsWindow')
mc.tabLayout('ToolsTabs')

#########################################################
##################    IMPORTING PANEL    ################
#########################################################
tabMenu = mc.columnLayout("Menu", adj=True)
separator_long = mc.separator(
                         height=10,
                         style='in')


mc.button(label="MyCustomScript", command = "my_custom_script_com()")

mc.setParent('..')
mc.showWindow()

#### My custom script ####
def my_custom_script_com(*args):
    super_bool_tool_ui()
    super_bool_tool_tut()

Ответы [ 3 ]

1 голос
/ 14 мая 2019

Это вечная проблема майя. Проблема в том, что вы используете строковое имя команды:

command = "please_print()"

Но «please_print» находится внутри run_my_custom_script_ui и выходит из области видимости при запуске функции. Для кнопки Maya не нужно вызывать функцию «please_print», когда вы нажимаете кнопку.

Если вы измените порядок и передадите сам объект функции без кавычек, все будет в порядке (добавив Функция кнопки, вы убедитесь, что она не выпадают из области видимости и уходят:

# this import does not need to be inside the function
import maya.cmds as mc

def run_my_custom_script_ui():

    # define this up here so it's in scope
    # when you want to call it below.  The *_
    # argument lets you ignore the default
    # argument which buttons always fire in Python

    def please_print(*_):
        print "OMG IT'S FINALLY WORKING!! YAY!!"

    if mc.window('my_script_ui', q=True, exists=True):
        mc.deleteUI('my_script_ui')
    else:
        mc.window('my_script_ui')

    mc.columnLayout("Menu", adj=True)

    mc.button(label="Please_print", command = please_print)

    mc.setParent('..')
    mc.showWindow()

Подробнее здесь: https://theodox.github.io/2014/maya_callbacks_cheat_sheet

1 голос
/ 14 мая 2019

Если я правильно понимаю, тогда вы можете получить второй подход к работе, переместив свою функцию. Что-то вроде:

def my_custom_script_com(*args):
    import maya.cmds as mc
    if mc.window('my_script_ui', q=True, exists=True):
        mc.deleteUI('my_script_ui')
    else:
        mc.window('my_script_ui')

    mc.columnLayout("Menu", adj=True)

    def please_print(): # define your function here
        print "OMG IT'S FINALLY WORKING!! YAY!!"

    mc.button(label="Please_print", command = "please_print()") # use the function

    mc.setParent('..')
    mc.showWindow()

Это потому, что функции должны быть определены до того, как они могут быть вызваны. Надеюсь, это поможет решить вашу проблему! Я также никогда не использовал maya, но я знаю, что в tkinter команда будет tkinter.Button(label="Please_print", command=please_print) без кавычек на please_print. Не уверен, применимо ли это здесь или нет!

Если вы предпочли бы переместить please_print() в глобальное пространство, вы бы отделили этот раздел в его собственную функцию (в отличие от подфункции функции, которая довольно нетипична). Это будет выглядеть так:

# make a global function
def please_print():
    print "OMG IT'S FINALLY WORKING!! YAY!!"

def my_custom_script_com(*args):
    import maya.cmds as mc
    if mc.window('my_script_ui', q=True, exists=True):
        mc.deleteUI('my_script_ui')
    else:
        mc.window('my_script_ui')

    mc.columnLayout("Menu", adj=True)

    mc.button(label="Please_print", command = "please_print()") # use the function

    mc.setParent('..')
    mc.showWindow()

Или, возможно, лучшим (с использованием нотации tkinter) будет:

# make a global function
def please_print():
    print "OMG IT'S FINALLY WORKING!! YAY!!"

def my_custom_script_com(*args):
    import maya.cmds as mc
    if mc.window('my_script_ui', q=True, exists=True):
        mc.deleteUI('my_script_ui')
    else:
        mc.window('my_script_ui')

    mc.columnLayout("Menu", adj=True)

    mc.button(label="Please_print", command = please_print) # assign function without quotes or parenthesis

    mc.setParent('..')
    mc.showWindow()
0 голосов
/ 15 мая 2019

Я исправил много вещей в вашем скрипте, попробуйте взглянуть на это. В вашем скрипте так много всего происходит, что я приведу несколько ссылок ниже: Как использовать значение ползунка в расчетах?

Одна вещь, которую я мог бы не сказать по другой теме: не используйте pymel, если вы просто используете его как maya.cmds Pymel действительно классный, но очень медленный.

Также, если вы разделяете свой скрипт на 'superbool.py', он должен работать следующим образом:

import superbool
superbool.super_bool_ui()

Наконец, старайтесь избегать строк, создающих ссылки для команд или элементов пользовательского интерфейса. Попробуйте использовать переменные, dict, class!


import maya.cmds as mc
import pymel.all as pma
from functools import partial

BOOLEANMODE_ADD = 1
BOOLEANMODE_SUBTRACT = 2
PRIMITIVE_CUBE = 0
PRIMITIVE_CYLINDER = 1
PRIMITIVE_SPHERE = 2
PRIMITIVE_CUSTOM = 3


def cleanUp ():
    mc.delete(constructionHistory=True)
    mc.delete("*_ctrl*")

def hider(option, *args):
    if option == 0:
        mc.hide()
    elif option == 1:
        mc.select ("*_ctrl*")
        mc.hide()
    elif option == 2:
        mc.select ("*_ctrl*")
        mc.showHidden()
        mc.select (clear=True)

def fixMaterial():
    # pma.hyperShade( assign="lambert1" )
    # works better with the command sets, jut put the SG you need
    sel = mc.ls(sl = True)
    if not mc.objExists('grey20'):
        shaLambert = mc.shadingNode('lambert', asShader = True, name = 'grey20')
        shaLambertSG = mc.sets(name = 'grey20SG', empty = True, renderable = True, noSurfaceShader = True)
        mc.connectAttr('grey20.outColor', 'grey20SG.surfaceShader')
    mc.sets(sel, edit = True, fe = shaLambertSG)

def triangulate():
    mc.polyTriangulate()

def creator(primitives, *args):
    selection = mc.ls(sl=True)
    for x in selection:
        if primitives == PRIMITIVE_CUBE:
            a = makeCube() #Create cube
        if primitives == PRIMITIVE_CYLINDER:
            a = makeCyl() #Create cyl 
        if primitives == PRIMITIVE_SPHERE:
            a = makeSphere() #Create sphere 
        if primitives == PRIMITIVE_CUSTOM:
            a = selection[1]  
            x = selection[0]
            mc.select(a)
        b = createController(a)
        meshConstrainer (b,a)
        operator(x,a) 
        mc.select(b)

def operator(meshA, meshB):
   booleanmode = get_boolean_mode()
   # is there a way to replace this pymel ?
   pma.polyBoolOp( meshA, meshB, op=booleanmode, n="basemesh" )
   fixMaterial()  #REMINDER: Need to be replaced with the actual assigned material and not with a lambert1 so for who is working with other materials can easyly keep using that


def get_boolean_mode(addRadioB=None, subRadioB=None):
    # should not be implemented as string.....
    if mc.radioButton('addRadio', query = True, select = True) :
        return BOOLEANMODE_ADD
    if mc.radioButton('subRadio', query = True, select = True) :
        return BOOLEANMODE_SUBTRACT
    return None

def makeCube():
    cubeTransform = mc.polyCube(n="cubetobool", w=1, h=1, d=1, sx=1, sy=1, sz=1)[0]
    return cubeTransform       

def makeCyl():
    cylTransform = mc.polyCylinder(n="cubetobool", r=1, h=2, sx=20)[0]
    return cylTransform   

def makeSphere():
    sphereTransform = mc.polySphere(n="cubetobool", r=1, sx=20, sy=20, cuv=2)[0]
    return sphereTransform    


def meshConstrainer(constrainer, constrained):   
    mc.scaleConstraint( constrainer, constrained, maintainOffset=True)
    mc.parentConstraint( constrainer, constrained, maintainOffset=True)


def createController(object):
    #object = pma.ls(sl=True) 
    pivotObj = mc.xform(object,query=True,t=True,worldSpace=True)
    edges = mc.filterExpand(mc.polyListComponentConversion(te=1),sm=32,ex=1) # convert edges to curve ancd create one object
    for edge in edges:
        vtx = mc.ls(mc.polyListComponentConversion(edge,fe=1,tv=1),fl=1)
        p1 = mc.pointPosition(vtx[0])
        p2 = mc.pointPosition(vtx[1])
        curves = mc.curve(n="line_ctrl_curve", d=1,p=(p1,p2))

    ctrl = mc.curve (n="bool_ctrl", d=1,ws=True, p=pivotObj)
    mc.xform (centerPivots=True)
    for curveEdge in mc.ls ("line_ctrl*"):
        mc.parent(curveEdge,ctrl, s=1, r=1)
        mc.rename(curveEdge, "shapeunused")


    transforms =  mc.ls(type='transform')
    deleteList = []
    for tran in transforms:
        if mc.nodeType(tran) == 'transform':
            children = mc.listRelatives(tran, c=True)
            if children is None:
                #print '%s, has no childred' %(tran)
                deleteList.append(tran)

    if not deleteList:           
       mc.delete(deleteList)
    return ctrl


def deleteUI(name, *args):
    mc.deleteUI(name)


#################TUTORIAL
def super_bool_tut():
    windowNameTut = "Tutorial"
    if mc.window(windowNameTut , exists=True):
        mc.deleteUI(windowNameTut)
    windowTutorial = mc.window(windowNameTut, title = windowNameTut, width = 400, height = 300, backgroundColor = [0.2, 0.2, 0.2])
    mainSubLayout = mc.columnLayout( "testColumn", adjustableColumn = True)
    lb_txt = "This tool is a super tool to make booleans wrote by Leonardo Iezzi. To make it works correctly, you need to have your base mesh already even if just a cube. "
    lb_txt += "With your base mesh selected just press one of the three buttons on the windows to subtract or add those primitives. "
    lb_txt += "If you want to use a custom mesh for the operation: select your base mesh then the custom one "
    lb_txt += "(it's important to pick your base mesh first) and then press the 'Use custom mesh' button. After you have done, select your base mesh and press 'Clean Up.'"
    mc.text("intro", label = lb_txt ,wordWrap= True, height = 100, backgroundColor = [0.2, 0.2, 0.2], align='left', parent = mainSubLayout)

    mc.separator(parent = "testColumn", height=20)
    mc.button("goit", label = "Got it", width = 120, height = 40, backgroundColor = [0.5, 0.5, 0.5], parent = mainSubLayout, command = partial(deleteUI, windowNameTut))

    mc.showWindow()

################################################################################################UI################################################# 
# @@@@@@@    THIS IS POLYSHIFTER!! I HAVE ADDED THIS AS A FUNCTION INSTEAD OF LEAVING IT UNINDENTED
def super_bool_ui():
    windowName = "SuperBool"
    w, h = (120, 200)
    if mc.window(windowName , exists=True):
        mc.deleteUI(windowName)
    window = mc.window( windowName, title= windowName, width = w, height = h)
    mainLayout = mc.columnLayout( "mainColumn", adjustableColumn = True)

    ################################################################################################UI#################################################
    gridl_01 = mc.gridLayout("nameGridLayout01", numberOfRowsColumns = (1,4), cellWidthHeight = (40,40), parent = mainLayout)
    btn_symb = mc.symbolButton("nameButton1", image = "polyCube.png", width = 40, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_01, command = partial(creator, PRIMITIVE_CUBE))
    mc.symbolButton("nameButton2", image = "polyCylinder.png", width = 40, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_01, command = partial(creator, PRIMITIVE_CYLINDER))
    mc.symbolButton("nameButton3", image = "polySphere.png", width = 40, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_01, command = partial(creator, PRIMITIVE_SPHERE))
    vl_column01 = mc.columnLayout("columnLayoutName01", adjustableColumn = True, backgroundColor = [0.2, 0.2, 0.2], p=mainLayout)
    mc.radioCollection("collection10", parent = vl_column01)
    subRadioB = mc.radioButton("subRadio", select = True, label = "Sub")
    addRadioB = mc.radioButton("addRadio", label = "Add")
    ################################################################################################UI#################################################
    mc.separator(parent = mainLayout, height=20)

    mc.button("customMeshB", label = "Use Custom Mesh", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = mainLayout, command = partial(creator, PRIMITIVE_CUSTOM))

    mc.separator(parent = mainLayout, height=20)
    ################################################################################################UI#################################################
    gridl_02 = mc.gridLayout("nameGridLayout03", numberOfRowsColumns = (1,3), cellWidthHeight = (53,40), parent = mainLayout)
    mc.button("hidSelB", label = "Hide Sel",  height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_02, command = partial(hider, 0))
    mc.button("hidAllB", label = "Hide All",  height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_02, command = partial(hider, 1))
    mc.button("showAll", label = "Show All",  height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_02, command = partial(hider, 2))

    mc.separator(parent = mainLayout, height=20)

    mc.button("clean", label = "Clean Up", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = mainLayout, command = cleanUp)

    mc.separator(parent = mainLayout, height=20)
    ################################################################################################UI#################################################
    ################################################################################################UI#################################################
    gridl_03 = mc.gridLayout("nameGridLayout02", numberOfRowsColumns = (1,2), cellWidthHeight = (80,40), parent = mainLayout)
    mc.button("triangB", label = "Triangulate", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_03, command = triangulate)
    mc.button("fixMatB", label = "FixMaterial", width = 120, height = 40, backgroundColor = [0.2, 0.2, 0.2], parent = gridl_03, command = fixMaterial)
    ################################################################################################UI#################################################
    mc.showWindow()


###################################################################
##################                              ###################
##################    END OF SUPER BOOL TOOL    ###################
##################                              ###################
###################################################################
###################################################################
##################                              ###################
##################   BEGINNING OF MY UI SCRIPT  ###################
##################                              ###################
###################################################################

#### My custom script ####
def my_custom_script_com(*args):
    super_bool_ui()
    super_bool_tut()

# Create a custom floating window with 
if mc.window('ToolsWindow', q=True, exists=True):
    mc.deleteUI('ToolsWindow')
if mc.workspaceControl('ToolsWorkspaceControl', q=True, exists=True):
    mc.deleteUI('ToolsWorkspaceControl')
mc.window('ToolsWindow')
mainL = mc.columnLayout()
tabLayout = mc.tabLayout('ToolsTabs', p=mainL)

#########################################################
##################    IMPORTING PANEL    ################
#########################################################
tabMenu = mc.columnLayout("Menu", adj=True, p=tabLayout)
separator_long = mc.separator(
                         height=10,
                         style='in', p=tabMenu)

mc.button(label="MyCustomScript", command = my_custom_script_com, p=tabMenu)
mc.showWindow()
...