2013-08-03 1 views
0

это мой код:# NameError: глобальное имя 'time1' не определен # майа-питон

def animate(*arg): 
    cvList = [] 
    myList = cm.ls(sl =True) 
    randList1 = [rand.uniform(-10,10)for items in range(10)] 
    for i in myList: 
     cvList = cm.ls(i+".cv[:]" , flatten = True) 
    for j in cvList: 
     cm.setKeyframe(j , ".cv[0].xValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].xValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].yValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].yValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].zValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].zValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].xValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].xValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].yValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].yValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].zValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].zValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 


animWindow = cm.window(t = 'Animation controls' , w = 150 , menuBar = True , bgc = [.2,.2,.2]) 
cm.menu(l = 'About' , tearOff = False) 
cm.menuItem(l = 'Version 1.0.0') 
cm.columnLayout() 
cm.text(l = 'Time 1' , w = 150) 
time1 = cm.intField() 
cm.text(l = 'Time 2' , w = 150) 
time = cm.intField() 
cm.button(l = 'Set key' , c = animate , w = 150, bgc = [.3,.3,.3]) 
cm.showWindow(animWindow) 

это ошибка я получил:

# NameError: global name 'time1' is not defined # 

я знаю, после этого майа Wanna скажи time2 тот же

я использовал это в этом, и это сработало:

def tinyRandomize(*arg): 
    myList = cm.ls (sl = True) 
    randoms = [rand.uniform(cm.floatField(Ceil, q = True , v = True),0.5)for i in range(30)] 
    for objects in myList: 
     cm.xform('%s.cv[0]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[1]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[2]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[3]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[4]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[5]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[6]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[7]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[8]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[9]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[10]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[11]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[12]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[13]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[14]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[15]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[16]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[17]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[18]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[19]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 
     cm.xform('%s.cv[20]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))]) 

Я добавил gui для этого def и полностью обработан

, пожалуйста, помогите мне.

наилучшими пожеланиями

+0

Вам нужно передать время1, time2 – sihrc

+1

Почему вы пишете функцию с 21 почти идентичными копируемыми строками вместо двухстрочного цикла? – user2357112

+0

Ваш первый фрагмент кода окажется внутри класса? – user2357112

ответ

0

Я обнаружил, что это проще, чище и более кратким, чтобы иметь класс при создании простых интерфейсов с Майей по умолчанию элементов пользовательского интерфейса. Они вызываются немедленно, когда определены в init(), и ваши объекты интерфейса теперь находятся в вашей локальной области.

import maya.cmds as cm 
import random as rand 

class RandomAnimation(): 
    def __init__(): 
     self.animWindow = cm.window(t = 'Animation controls' , w = 150 , menuBar = True , bgc = [.2,.2,.2]) 
     cm.menu(l = 'About' , tearOff = False) 
     cm.menuItem(l = 'Version 1.0.0') 
     self.cLayout = cm.columnLayout() 
     self.timeText = cm.text(l = 'Time 1' , w = 150) 
     self.time1 = cm.intField() 
     self.cm.text(l = 'Time 2' , w = 150) 
     self.time = cm.intField() 
     self.myButton = cm.button(l = 'Set key' , c = self.animate , w = 150, bgc = [.3,.3,.3]) 
     cm.showWindow(animWindow) 
     # Since the ui is in __init__() it will be ran once the class is instantiated.. 

    def animate(*args): 
     # This will gather all of the cvs in all of your selected curves.. 
     for cv in [for j in [cm.ls(i + ".cv[:]", fl=1) for i in cm.ls(sl=True)]: 
      # This will move all the cvs randomly.. 
      cm.xform(cv, r=1, t=[rand.uniform(-1, 1), rand.uniform(-1, 1), rand.uniform(-1, 1)]) 

Проверить this за более подробное объяснение по классам.

0

вы указали переменную время1 вне определения анимировать. Когда функция пытается запустить, она не знает, что такое time1.

@ Ответ Argiri - это правильный путь в долгосрочной перспективе - включение функций интерфейса и обратного вызова в класс - это более чистый и лучший способ организовать код.

Чтобы сделать это действительно ясно, что вызывает проблему, попробуйте следующее:

from functools import partial 
import random as rand 

def animate(time1, time2, ignore): 
    print time1, time2, ignore 
    cvList = [] 
    myList = cm.ls(sl =True) 
    randList1 = [rand.uniform(-10,10)for items in range(10)] 
    for i in myList: 
     cvList = cm.ls(i+".cv[:]" , flatten = True) 
    for j in cvList: 
     cm.setKeyframe(j , ".cv[0].xValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].xValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].yValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].yValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].zValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[0].zValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].xValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].xValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].yValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].yValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].zValue" , t = cm.intField(time1 , query = True , value = True) , v = rand.choice(randList1)) 
     cm.setKeyframe(j , ".cv[1].zValue" , t = cm.intField(time2 , query = True , value = True) , v = rand.choice(randList1)) 


animWindow = cm.window(t = 'Animation controls' , w = 150 , menuBar = True , bgc = [.2,.2,.2]) 
cm.menu(l = 'About' , tearOff = False) 
cm.menuItem(l = 'Version 1.0.0') 
cm.columnLayout() 
cm.text(l = 'Time 1' , w = 150) 
time1 = cm.intField() 
cm.text(l = 'Time 2' , w = 150) 
time2 = cm.intField() 
cm.button(l = 'Set key' , c = partial(animate, time1, time2) , w = 150, bgc = [.3,.3,.3]) 
cm.showWindow(animWindow) 

модуль functools включает в себя объект, называемый частичный, который котрый сводит к набор аргументов с функцией, чтобы они могли быть вызываемые вместе. Установив команду кнопки на частичную в момент запуска кода, вы убедитесь, что при обратном вызове объекты intField идут в функцию - поэтому, когда def запрашивает два поля, что они есть, он знает, как чтобы найти их.

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

Возможно, вы должны проверить Mechtley's book на майа-питоне (особенно в главе о графическом интерфейсе). Есть также полезные дискуссии herehere, и here

PS: Кто-то, возможно, опубликовать исправление, которое ставит «глобальный» перед time1 и time2 и «глобальной time1, time2» внутри живого опр. Не делайте этого. Глобал = зло.

+0

haha ​​amen sir to the globals = evil! –