首页 > 解决方案 > Python和Maya:访问按钮启动的另一个函数中的变量

问题描述

我在 Maya 中有一个简单的 python/pymel 脚本,可以帮助用户复制通道框中选定属性的值,并在用户选择另一个对象和相同或其他属性后粘贴它们。

有 2 个按钮,一个用于复制属性,一个用于粘贴属性。因此,首先,用户选择具有要从中复制的属性的对象,然后在通道框中选择这些属性。然后他单击第一个按钮:它启动一个函数,该函数创建一个包含这些选定属性的值的列表。然后,他选择一个或多个对象,以及通道框中的属性,他要粘贴他复制的内容。他单击第二个按钮来粘贴这些值。我的问题来了:我找不到访问使用第一个函数创建的列表的方法。

这是我的代码:

import pymel.core as pm
import pymel.core.windows as pw

#Here I define the functions getSelectedChannels(), copyAttrs(), and pasteAttrs()
#It works weel, unrelevant for my problem


#1, creates the list of values :
def copy_attr(*args):

    attrs = getSelectedChannels() #function to get the attributes names from the selection in the channel box
    attrsValues = copyAttrs(attrs)   #function to copy their values in the list attrsValues 
    return attrsValues               #at this point, my list is ok



#2, paste the values, but I can't access to the list
def paste_attrs(attrsValues,*args):

    attrs = getSelectedChannels()
    pasteAttrs(attrs,attrsValues)


#############################################################
#UI

#check if windows already exists
if pw.window(windowName, exists = True):
    pw.deleteUI(windowName)

#window creation & definition
myWindow = pw.window(windowName, t  = scriptName + " " + scriptVersion , w=100, h=100,)
pw.columnLayout(adj = True, columnAlign = "center")
pw.separator(h = 20)
pw.text(titleWindow)
pw.separator(h = 20)


pw.text("First, select the attributes you want")
pw.text("to copy from the channel box\n")
pw.text("Then, select the attributes in the channel  ")
pw.text("box where you wantto paste them\n")
pw.text("Finally, choose paste or reversed paste")
pw.separator(h = 20)

pw.gridLayout( numberOfColumns=3, cellWidthHeight=(110, 25) )

attrValues = pw.button(l = button_copy,width = 60, command = pm.Callback(copy_attr)) #attrValues doesn't correspond to the attrsValues list the function returned, that's where it fails
pw.button(l = button_paste,width = 60, command = pm.Callback(paste_attrs, attrValues )) 
pw.separator(h = 10)


pw.showWindow(myWindow)

标签: pythonfunctionvariablesbuttonmaya

解决方案


您的问题来自于您返回属性值列表,但您没有将其保存在任何变量中。一旦函数返回,数据就会丢失。您需要找到一种方法来在函数调用之间保留数据。你有两种可能,一种不好,一种更好。不好的是使用全局变量,在你的情况下你必须使用:

def copy_attr(*args):
    global attrsValues
    attrs = getSelectedChannels()
    attrsValues = copyAttrs(attrs) 

def paste_attrs(*args):
    global attrsValues
    attrs = getSelectedChannels()
    pasteAttrs(attrs,attrsValues)

如前所述,这是一个糟糕的解决方案,因为全局变量可能会导致麻烦。更好的解决方案是使用类并在类中创建窗口并将函数定义为类方法。这样您可以将数据保存在类实例变量中,而不必使用全局变量。


推荐阅读