You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Maya脚本问题:点击按钮无法打印textField输入文本如何解决?

问题描述

我正在编写Maya脚本,需要将textField中输入的名称用于文件名。编写了测试脚本,但点击按钮时无报错却仅打印空内容。

测试代码如下:

import maya.cmds as cmds

def pritest(*args):
    print(namepull)
#    Create a window with a some fields for entering text.
#
window = cmds.window()
cmds.rowColumnLayout( numberOfColumns=2, columnAttach=(1, 'right', 0), columnWidth=[(1, 100), (2, 250)] )
cmds.text( label='Name' )
#
name = cmds.textField()
cmds.textField(name, e=True,ed=True)
namepull = cmds.textField(name,q=True,tx=True)
#
cmds.button('Go',en=True,c=pritest)

cmds.showWindow( window )

希望实现点击按钮后打印textField中输入的任意文本,恳请提供帮助。


修复方案

问题核心是文本获取时机错误:你在窗口初始化时就执行了namepull = cmds.textField(name,q=True,tx=True),此时用户还未输入内容,namepull被固定为空字符串。点击按钮时打印的是这个提前存储的空值,而非用户输入后的最新内容。

修改后的代码如下:

import maya.cmds as cmds

def pritest(*args):
    # 点击按钮时才实时获取textField的最新文本
    current_input = cmds.textField(name, q=True, tx=True)
    print(current_input)

window = cmds.window()
cmds.rowColumnLayout( numberOfColumns=2, columnAttach=(1, 'right', 0), columnWidth=[(1, 100), (2, 250)] )
cmds.text( label='Name' )

name = cmds.textField()
# 默认textField就是可编辑状态,这行可省略
# cmds.textField(name, e=True,ed=True)

cmds.button('Go', en=True, c=pritest)

cmds.showWindow( window )

额外优化说明:

  • cmds.textField(name, e=True,ed=True)可以删除,因为创建textField时默认开启编辑权限。
  • 若后续编写复杂窗口,建议用类来管理控件引用,避免依赖全局变量,提升代码可维护性。

内容的提问来源于stack exchange,提问作者Sebastian Camargo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:19:57