python - 输入数字时需要帮助制作按钮以执行 for 循环
问题描述
我正在尝试使用 Python 在 Maya 中创建一个按钮,当您输入数字时,for 循环将循环多次。例如,我将 5 放入框中,因此 for 循环将循环 5 次,从而产生 50 个立方体,因为它适用于范围 (1,10) 内的 i。
这是我的代码:
import maya.cmds as cmds
import random
handle = "cubeUI"
if cmds.window(handle, exists=True):
print ("deleting old window...\n")
cmds.deleteUI(handle)
cmds.window(handle, title = "make random cubes")
cmds.columnLayout()
cmds.text(label = "amount")
amount_range_text_field = cmds.intField()
cmds.button(label = "random cube", command = "giveMeCube()")
cmds.showWindow(handle)
def giveMeCube():
cmds.polyCube()
amount_range = cmds.intField( amount_range_text_field, query=True, value = True )
for i in range (1,10):
print i
temp = cmds.polyCube()
cmds.xform(temp, t = (random.uniform(-1 *amount_range, amount_range),
random.uniform(-1 * amount_range, amount_range), random.uniform(-1 *
amount_range, amount_range) ) )
解决方案
我的回答有点复杂,Green Cell 的回答应该适合你。这是一个关于您应该如何认为您的脚本更“干净”的示例我已经添加了一些注释来帮助理解为什么会这样
import maya.cmds as cmds
# This module can pass data throughts ui
from functools import partial
import random
# your function that have the amount set as variable that you can set easily :
# giveMeCube(2) result into 20 cubes
def giveMeCube(amount_range = 1):
nb = amount_range * 10
for i in range (nb):
print(i)
temp = cmds.polyCube()
cmds.xform(temp, t = (random.uniform(-1 *amount_range, amount_range),
random.uniform(-1 * amount_range, amount_range), random.uniform(-1 *
amount_range, amount_range) ) )
# this function is just to separate your function from ui control
# so if you want to use giveMeCube in command line or in another script, you don't have your ui polluting the function
# *args is here because the command flag from maya ui give a default True as last argument that need to be dismissed
# most of the time, im putting the intfield query in another function
def uiGiveMeCube(fieldname, *args):
amount = cmds.intField(fieldname, q=True, value=True)
giveMeCube(amount)
def showUI():
handle = "cubeUI"
if cmds.window(handle, exists=True):
print ("deleting old window...\n")
cmds.deleteUI(handle)
cmds.window(handle, title = "make random cubes")
cmds.columnLayout()
cmds.text(label = "amount")
amount_range_text_field = cmds.intField(value=1, min=1)
# you should not use string to set your function
# you could have write : cmds.button(label = "random cube", command = giveMeCube)
# so how partial is used : partial(function, argument1, argument2, ...etc)
cmds.button(label = "random cube", command = partial(uiGiveMeCube, amount_range_text_field))
cmds.showWindow(handle)
showUI()
推荐阅读
- c# - 使用 Azure 时 Visual Studio 中的 System.Net.Sockets.SocketException
- amazon-web-services - aws 云形成嵌套堆栈导出/导入值
- android - Gradle 同步失败,因为 ImmutableMultiMap 无法访问其超类
- sql-server - 在 SQL Server 的存储过程中执行时,新创建的变量显示为空值
- ios - 页面更改控制当前页面点的半径
- object - 地图内的 Lodash _.omit 函数
- java - 处理:声音文件在循环中,但只想播放一次
- openoffice-calc - 将多个电子表格中的数据读入数据库
- image - Rust - 图像箱:保存图像缓冲区的问题
- javascript - 从 React.js 中的 json 文件中获取数据