+1 tag for Google+

Sunday, 30 July 2017

A Script to Randomise Maya UI Button Labels and Return Labels

In a reply to a question on StackOverflow, I have created the following fun block of code.


import maya.cmds as mc
import random, string
from functools import partial

def randomButtonTest():
    buttonsList = []
    numButtons = 5
    winName = 'randomButtonWin'
    winWidth = 250
    statusTfgName = 'myStatusTfg'
    buttonLabelLength = 10

    def generateRandomLabel(myLength):
        # generates a random string of characters of myLength
        randomCandidatesList = list(string.ascii_letters + string.digits)
        random.shuffle(randomCandidatesList)
        randomCandidatesStr = ''.join(randomCandidatesList)
        return ''.join([randomCandidatesStr[random.randint(0,len(randomCandidatesStr)-1)] for x in range(myLength)])

    def reportButtonLabel(whichButton, *args):
        buttonLabel = mc.button(whichButton, q=True, label=True)
        print 'reportButtonLabel: clicked - %s' % buttonLabel
        mc.textFieldGrp(statusTfgName, e=True, text=buttonLabel)
        return

    def randomiseButtonClicked(*args):
        mc.textFieldGrp(statusTfgName, e=True, text='')
        for thisButton in buttonsList:
            currentLabel = mc.button(thisButton, q=True, label=True)
            newLabel = '%s: %s' %(currentLabel.split(':')[0], generateRandomLabel(buttonLabelLength))
            mc.button(thisButton, e=True, label=newLabel)
        return

    # build UI
    if mc.window(winName, exists=True):
        mc.deleteUI(winName)
    mc.window(winName, title='Randon Button Labels', w=winWidth )
    mc.columnLayout(w=winWidth)

    # create numButtons number of buttons
    for buttonId in range(numButtons):
        buttonsList.append(mc.button(label='button %i:'%buttonId, w=winWidth ))
        mc.button(buttonsList[-1], e=True, command=partial(reportButtonLabel, buttonsList[-1]))
    mc.text(label='')
    mc.textFieldGrp(statusTfgName, label='Button clicked', w=winWidth, columnWidth2=[winWidth*0.3, winWidth*0.65])
    mc.text(label='')
    mc.button('Randomise labels', w=winWidth, command=randomiseButtonClicked)

    randomiseButtonClicked()
    mc.window(winName, e=True, w=winWidth, h=150, resizeToFitChildren=True)
    mc.showWindow(winName)

randomButtonTest()
This code demonstrates how I handle passing of UI names to functions that can do query attributes contained in the UI, including their labels.

No comments:

Post a Comment