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

如何用Python/PySimpleGUI根据下拉框选项禁用指定输入字段

解决PySimpleGUI下拉框选择禁用对应输入框的问题

你的代码存在几个问题导致功能无法实现,以下是修正后的完整代码:

import PySimpleGUI as sg

layout = [
    [sg.Text('Filed 1:', size=(15,1)), sg.Combo(['DisableField2', 'DisableField3', 'DisableField2&3'], size=(25, 1), key='FIELD1')],
    [sg.Text('Field 2:', size=(15,1)), sg.Input(key='FIELD2', size=(25,1))],
    [sg.Text('Field 3:', size=(15,1)), sg.Input(key='FIELD3', size=(25,1))],
]

window = sg.Window('MAIN',  layout, finalize=True,element_justification='c')

while True:
    event, values = window.read()
    print(event, values)

    if event == sg.WIN_CLOSED or event == 'Exit':
        break

    elif event == 'FIELD1':
        # 若需要将下拉框选项转为大写,可取消下面注释
        # window['FIELD1'].update(values['FIELD1'].upper())
        selected_option = values['FIELD1']
        # 先恢复两个输入框为可用状态,避免之前的禁用残留
        window['FIELD2'].update(disabled=False)
        window['FIELD3'].update(disabled=False)
        # 根据选中选项禁用对应输入框
        if selected_option == 'DisableField2':
            window['FIELD2'].update(disabled=True)
        elif selected_option == 'DisableField3':
            window['FIELD3'].update(disabled=True)
        elif selected_option == 'DisableField2&3':
            window['FIELD2'].update(disabled=True)
            window['FIELD3'].update(disabled=True)
window.close()

关键修改点:

  1. 移除了未定义的result2变量调用,避免运行报错
  2. 不再用event判断选中选项,而是通过values['FIELD1']获取下拉框实际选中的值
  3. 每次处理下拉框选择时,先恢复两个输入框的可用状态,确保切换选项时状态正确
  4. 修正了原代码中最后一个条件重复更新FIELD2的错误,改为正确禁用FIELD3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:20:36