问题
I want to print the value of intField given by user in maya using python.
code
import maya.cmds as cmds
def fun(number):
print(number)
cmds.window()
cmds.columnLayout()
num = cmds.intField(changeCommand = 'fun()')
cmds.showWindow()
User will enter value in intField and i want to print that value
回答1:
You have to use lambda or partial :
import maya.cmds as cmds
from functools import partial
# Here is how i layout this kind of case :
# First the function that is not related to the ui
def anyFuction(number):
print(number)
# i create a parser who will query value by default but some ui elements may use other arguments
# I put kwargs for example if you want to query another flag (for some simple ui, i even put as argument the cmds.intField)
# note that i had if your function as some other things to pass throught
# if you have multiple fields to query you can bind the function into another function example below the code
def queryIntfield(function='', uiNameElem, *args, **kwargs):
if kwargs:
v = cmds.intField(uiNameElem, q=True, **kwargs)
else:
v = cmds.intField(uiNameElem, q=True, v=1)
if len(args) > 1:
function(v, *args)
elif function = '':
return v
else:
function(v)
cmds.window()
cmds.columnLayout()
# create the field to get his name : num
num = cmds.intField(changeCommand = '')# do not put a function in comma
# edit the command placeholder
cmds.intField(num, e=1, changeCommand = partial(ui_queryIntfield, anyFuction, num))
cmds.showWindow()
----- Example 2
'''
# Example 2
# Here is how i layout this kind of case :
# First
def anyFuction(number):
print(number)
# Second
def queryIntfield(uiNameElem, *args, **kwargs):
if kwargs:
v = cmds.intField(uiNameElem, q=True, **kwargs)
else:
v = cmds.intField(uiNameElem, q=True, v=1)
return v
# Third, if it is a complex function, i duplicate the name anyFunction and add ui_ to know im binding this function with ui
def ui_anyFunction(uiNameElem, *args, **kwargs):
# Do some stuff
value = queryIntfield(uiNameElem)
# and other stuff
# .....
# ..............
anyFuction(value)
'''
回答2:
You can use a lambda or partial, or you can simply define your callback function in a scope where the UI element already exists so it knows the name of the UI:
import maya.cmds as cmds
def fun(number):
print(number)
cmds.window()
cmds.columnLayout()
num = cmds.intField()
def num_callback():
print cmds.intField(num, q=True, value=True)
cmds.intField(num, e=True, changeCommand = num_callback)
cmds.showWindow()
In general you want to avoid using the string form of callback assignment: it's a common source of problems where maya cannot find the function if you're not in the listener. More detail here
来源:https://stackoverflow.com/questions/48057577/how-to-print-the-value-of-intfield-in-maya-python