通过PyM获取、存储、设置和修改变换属性

2024-06-11 21:39:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做的是获取并存储用户移动的对象的变换,然后允许用户单击按钮返回用户设置的值。在

到目前为止,我已经找到了如何获取属性并设置它。但是,我只能得到和设置一次。有没有一种方法可以在运行一次的脚本中多次执行此操作?或者我必须继续重新运行脚本吗?对我来说,这是一个至关重要的问题。在

基本上:

btn1 = button(label="Get x  Shape", parent = layout, command ='GetPressed()')    
btn2 = button(label="Set x Shape", parent = layout, command ='SetPressed()')
def GetPressed():
    print gx #to see value
    gx = PyNode( 'object').tx.get() #to get the attr
def SetPressed(): 
    PyNode('object').tx.set(gx) #set the attr???

我不是百分之百地知道如何正确地做这件事,或者我是否走对了路?在

谢谢


Tags: to用户脚本objectdefbuttonlabelcommand
1条回答
网友
1楼 · 发布于 2024-06-11 21:39:38

您没有传递变量gx,因此SetPressed()将失败,如果您在运行整个过程之前尝试在侦听器中直接执行gx = ...行,那么它可能会偶尔运行,但它会不稳定)。您需要在您的SetPressed()函数中提供一个值,以便set操作可以使用。在

作为旁白,使用字符串名称来调用按钮函数不是一个好方法,当从侦听器执行代码时,代码可以工作,但是如果绑定到函数中,则代码将不起作用:当为函数使用字符串名称时,Maya只会在它们位于侦听器命令所在的全局名称空间中找到它们,但很难从中访问它们其他功能。在

下面是一个最小化的示例,说明如何通过将所有函数和变量保留在另一个函数中来实现这一点:

import maya.cmds as cmds
import pymel.core as pm

def example_window():

    # make the UI

    with pm.window(title = 'example') as w:
        with pm.rowLayout(nc =3 ) as cs:
            field = pm.floatFieldGrp(label = 'value', nf=3)
            get_button = pm.button('get')
            set_button = pm.button('set')

    # define these after the UI is made, so they inherit the names
    # of the UI elements

    def get_command(_):
        sel = pm.ls(sl=True)
        if not sel:
            cmds.warning("nothing selected")
            return
        value = sel[0].t.get() + [0]
        pm.floatFieldGrp(field, e=True, v1= value[0], v2 = value[1], v3 = value[2])


    def set_command(_):
        sel = pm.ls(sl=True)
        if not sel:
            cmds.warning("nothing selected")
            return
        value = pm.floatFieldGrp(field, q=True, v=True)
        sel[0].t.set(value[:3])


    # edit the existing UI to attech the commands.  They'll remember the UI pieces they
    # are connected to 

    pm.button(get_button, e=True, command = get_command)
    pm.button(set_button, e=True, command = set_command)

    w.show()

#open the window
example_window()

一般来说,在做mayagui时,这种事情是最棘手的一点,你需要确保所有函数和处理程序等都能看到对方并能共享信息。在本例中,函数通过在UI存在后定义处理程序来共享信息,这样它们就可以继承UI片段的名称并知道要处理什么。还有其他方法可以做到这一点(类是最复杂和最复杂的),但这是最简单的方法。关于如何做到这一点还有更深入的研究here

相关问题 更多 >