我已經創建了一個簡單的重命名腳本,但我想問一些建議,以便我可以優化編碼以及珩磨我的python腳本。下面是現在的代碼的一小部分...全局變量定義失敗
雖然這可能不是我的觀點的問題,但除了我在下面陳述的兩個函數之外,我已經認識到幾乎所有的函數,他們包含objects = cmds.ls(selection=True)
儘管我不介意重複鍵入,但我確實有更好的方法來糾正這個問題。
但是,當我在類函數之前嘗試使它們成爲全局函數時,它能夠運行,直到我厭倦執行其中一個函數時,它會提示錯誤,說明global name 'objects' is not defined
或'對象未定義'等。
相關的,有什麼建議嗎?
class mainWindow(QDialog):
def __init__(self, parent=None):
super(mainWindow, self).__init__(parent)
self.resize(300,225)
self.initUI()
self.createConnections()
def searchReplace(self):
wordSearch = str(self.searchTxt.text())
wordReplace = str(self.replaceTxt.text())
objCnt = cmds.ls(sl=True, sn=True)
if len(objCnt) == 0:
self.searchTxt.clear()
self.replaceTxt.clear()
cmds.warning('Nothing is selected')
else:
for wordString in sorted(objCnt):
if wordSearch in wordString:
newWordString = wordString.replace(wordSearch, wordReplace)
cmds.rename(wordString, newWordString)
self.searchTxt.clear()
self.replaceTxt.clear()
print '%s' %wordString + " has changed to : " + "%s" %newWordString
def addPrefix(self):
objects = cmds.ls(selection=True)
pfx = str(self.prefixTxt.text())
for item in objects:
if pfx == "":
cmds.warning('No prefix values in the field')
else:
cmds.rename(item, pfx + "_" + item)
self.prefixTxt.clear()
print 'Prefix added: %s_' %pfx
def addSuffix(self):
objects = cmds.ls(selection=True)
sfx = str(self.suffixTxt.text())
for item in objects:
cmds.rename(item, item + "_" + sfx)
self.suffixTxt.clear()
print 'Suffix added: _%s' %sfx
def numPadding(self):
objects = pm.ls(selection=True)
num = self.numTxt.text()
padding = self.paddingTxt.text()
if num != "" and padding !="":
try:
for currentWordStr in objects:
pad = ("%%0%ii" % int(padding)) % int(num)
newWordStr = currentWordStr.rename(currentWordStr.name() + "_" + pad)
except Exception:
self.numTxt.clear()
self.paddingTxt.clear()
cmds.warning('Input numerical values only')
else:
cmds.warning('Entries of Num or Padding are empty')
def selectHierarchy(self):
sel = cmds.ls(selection = True)
selCnt = len(sel)
if int(selCnt) == 0:
cmds.warning('Nothing is selected')
else:
objHierarchy = cmds.listRelatives(ad=True, type='transform', fullPath=True)
cmds.select(sel, objHierarchy)
def clearHierarchy(self):
sel = cmds.ls(selection = True)
selCnt = len(sel)
if int(selCnt) != 0 :
objHierarchy = cmds.select(clear=True)
else:
cmds.warning('Selection is empty. Nothing to be cleared')
您好!如果我正確理解你的帖子,這是你開始使用的代碼,這很好。你能否也請張貼你試過的是什麼導致了全球名稱錯誤?另外,你有沒有考慮過使用類變量? – Nacho
@Nacho我試圖添加'全局對象'和'objects = cmds。ls(selection = True)'就在'class mainWindow(QDialog):'的行之前,所有其他函數(不包括select和clear層次結構),我總是得到'#RuntimeError:No object matches name',如果我我選擇了2個物品(cube1有一個小孩 - cube2)。此外,它只編輯/重命名父代而不是孩子......順便說一下,你如何使用類變量?老實說,我對理解'def/class test(xxx)'的能力還是很弱,在這裏,除了self之外,我還無法理解我是否加入了其他變量...... – dissidia