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

Python动态变量名遍历:对话框复选框动态勾选问题

问题描述

我正在开发一款应用,功能是根据文本文件中的唯一条目数量动态生成复选框;用户输入值后,若与某个复选框名称匹配则勾选该复选框。

我使用的GUI框架支持对话框创建与事件处理,但勾选复选框需要用类似dialog.fixtureDictionary['fixtureName_0'].value = True的代码:其中dialog是对话框窗口,fixtureDictionary['fixtureName_0']是复选框名称,value=True用于勾选。

运行代码时,对话框事件处理器无法识别fixtureDictionary['fixtureName_0']对应的实际值(比如T30),反而会寻找名为fixtureDictionary的变量。

作为Python新手,我知道动态命名变量不是最佳实践,但脚本里每个复选框必须有唯一名称。请问如何为dialog."something".value传入动态名称?

核心代码
def verifyPartAndVMR(partInformation):

    fixtureDictionary = {}
    fixturePieceNo = 0

    fixtureFile = open(str(fixtureFileDirectory) + '/FixtureList_' + partInformation['partNumber'] + '.txt', "r")
    for aPiece in fixtureFile:
        fixtureDictionary['fixtureName_' + str(fixturePieceNo)] = aPiece.strip()
        fixturePieceNo += 1     
    fixtureFile.close()

    dialog=gom.script.sys.create_user_defined_dialog (content = buildDialog(fixtureDictionary))
    
    def dialog_event_handler(widget):
    
        while validScan(dialog.input_scanner.value):
            if dialog.input_scanner.value in fixtureDictionary.values():
                dialog.fixtureDictionary['fixtureName_0'].value = True
              
    dialog.handler = dialog_event_handler
    gom.script.sys.show_user_defined_dialog (dialog=dialog)

    return 1    


def buildDialog(fixtureDictionary):

    fixturePieceNo = 0

    dialog = createBlankForm(500, 500, 10, 10)
    dialog += addContinuousText(0,0,'<html><p align="center"><span style="font-size:12pt; color:#000000;">Example Text</span></p><p align="center" style="-qt-paragraph-type:empty;       font-weight:600; color:#ff0000;"><br/></p><p align="center"><span style="font-size:20pt; font-weight:600; color:#ff0000;">ABC123</span></p></html>')
    dialog += addInputField(0,1, 'input_scanner')
    dialog += addVerticalSpacer(1,2,1)

    for eachPiece in fixtureDictionary:
        dialog += addCheckBox(0, 3 + fixturePieceNo, fixturePieceNo, fixtureDictionary['fixtureName_' + str(fixturePieceNo)])
        fixturePieceNo += 1
    
    dialog += addVerticalSpacer(1,8,2)
    dialog += addButton(0,9, 1, '', 'ok')
    dialog += addButton(1,9, 2, '', 'cancel')

    return dialog + '</content></dialog>'


def createBlankForm(width, height, numRows, numCols):

    blankForm='<dialog>' \
    '<title>Test Dialog</title>' \
    '<style></style>' \
    '<control id="Empty"/>' \
    '<position></position>' \
    '<embedding></embedding>' \
    '<sizemode></sizemode>' \
    '<size width="' + str(width) + '" height="' + str(height) + '"/>' \
    '<content columns="' + str(numCols) + '" rows="' + str(numRows) + '">'

    return blankForm


def addCheckBox(colPosition, rowPosition, instance, checkBoxName):

    checkBox =  '<widget type="input::checkbox" rowspan="1" columnspan="1" row="' + str(rowPosition) + '"column="' + str(colPosition) + '">' \
                '   <name>' + checkBoxName + '</name>' \
                '   <tooltip></tooltip>' \
                '   <value>false</value>' \
                '   <title>' + checkBoxName + '</title>' \
                '</widget>'  
                
    return checkBox
解决方案

问题出在你试图直接通过dialog.fixtureDictionary['fixtureName_0']访问复选框,但Python会把fixtureDictionary当成dialog的一个属性,而不是你定义的字典变量。要动态访问对象的属性,需要用Python内置的getattr()函数。

修改步骤:

  1. 在事件处理器中,先根据用户输入的值反向查找字典中对应的键,再通过getattr获取目标复选框并勾选:
# 替换dialog_event_handler内的错误代码
input_value = dialog.input_scanner.value
for key, checkbox_name in fixtureDictionary.items():
    if checkbox_name == input_value:
        # 动态获取对话框上的复选框控件
        target_checkbox = getattr(dialog, checkbox_name)
        # 勾选复选框
        target_checkbox.value = True
        break
  1. 另外可以优化buildDialog中的循环逻辑,避免手动维护计数变量:
# 替换buildDialog里的for循环
for idx, (key, checkbox_name) in enumerate(fixtureDictionary.items()):
    dialog += addCheckBox(0, 3 + idx, idx, checkbox_name)

这样既解决了动态访问控件的问题,也让代码更简洁易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:45:08