是否有一个选项可以将数据从UI窗口接收到变量?

2024-04-27 13:52:49 发布

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

我看到可以打印用户界面窗口中写入的数据,但是,当我在互联网上搜索时,没有一个选项是这样的,将数据检索到变量中。在

这是一个非常简单的窗口代码- '

def printTxtField ( fieldID ):

    print cmds.textField( fieldID, query=True, text=True)

winID = 'kevsUI'


if cmds.window(winID, exists=True):

    cmds.deleteUI(winID)


cmds.window(winID)

cmds.columnLayout()


whatUSay = cmds.textField()
cmds.button(label='Confirm', command='printTxtField(whatUSay)')

cmds.showWindow()

'

我想在按下confirm按钮后,将文本字段中的数据检索到变量中。在

在cmds.button命令行,可以在命令中看到-'print TxtField'。 我知道如果有一个选项可以打印在文本字段中写入的内容,那么必须有一个将其放入变量的选项。但是,我没有发现是的。是的有人知道怎么做吗?在

对不起,前夫。问题。在


Tags: 数据文本true选项buttonwindow用户界面textfield
3条回答

必须使用部分模块通过按钮命令(或lambda函数)传递变量

from functools import partial

同样的问题是:maya python + Pass variable on button press

这是有可能的,但是在你的方式上有几个问题。@DrHaze的例子展示了正确的做法,即使用实际的python函数而不是字符串。在

您还需要考虑不同函数的可见性:在监听器中,所有代码都放在一个地方,很容易让事情正常工作,但是一旦涉及到多个函数或模块,跟踪gui小部件名称就变得更加困难。在

对于小型工具,您可以定义回调函数,即按钮使用的回调函数,在本例中,就在创建gui小部件的位置。这将使用python的规则closures为您跟踪小部件:

def window_example(title):
    if cmds.window(title, exists=True):
        cmds.deleteUI(title)
    win = cmds.window(title)
    cmds.columnLayout()
    whatUSay = cmds.textField()

    #defining this hear gives it access to 'whatUSay'
    def print_text_contents(ignore):
        print cmds.textField( whatUSay, query=True, text=True)

    cmds.button(label='Confirm', command=print_text_contents)
    cmds.showWindow(win)
window_example('kevsUI')

对于较长的工具,您可能希望了解如何使用类来执行此操作。在

以下是much more background info一些不同的策略。在

来自Python doc

print evaluates each expression in turn and writes the resulting object to standard output. If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written.


简单来说:

print语句在写入表达式后需要一个表达式。这可以是一个字符串,int,object。。。在

就您而言:

printTxtField函数中打印的是函数(cmds.textField( fieldID, query=True, text=True))的返回值。在

写这篇文章时:

cmds.textField( fieldID, query=True, text=True)您正在告诉Maya:

  1. 查找名为fieldID值的textField
  2. 对其进行查询(查询标志设置为True
  3. 查询它的文本(里面写了什么)
  4. 返回此值

总结:

不用打印返回值,您可以轻松地将该值赋给变量:myVar = cmds.textField( fieldID, query=True, text=True)


修改后的代码:

def printTxtField ( fieldID ):
    #here is the modification made
    myVar = cmds.textField( fieldID, query=True, text=True)

我已经对您的代码进行了注释和重新组织,使其更干净:

^{pr2}$

相关问题 更多 >