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

如何修复PySimpleGUI中的TypeError: cannot unpack non-iterable Button object错误

解决PySimpleGUI加载报错TypeError问题

报错信息

Traceback (most recent call last):
  File "D:\Python\Lavoro.py", line 89, in <module>
    event = window.read()
            ^^^^^^^^^^^^^
  File "D:\Python\venv\Lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 10075, in read
    results = self._read(timeout=timeout, timeout_key=timeout_key)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\venv\Lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 10146, in _read
    self._Show()
  File "D:\Python\venv\Lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9886, in _Show
    StartupTK(self)
  File "D:\Python\venv\Lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 16866, in StartupTK
    _convert_window_to_tk(window)
  File "D:\Python\venv\Lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 16753, in _convert_window_to_tk
    PackFormIntoFrame(window, master, window)
  File "D:\Python\venv\Lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 14943, in PackFormIntoFrame
    width, height = element_size
    ^^^^^^^^^^^^^
TypeError: cannot unpack non-iterable Button object

问题代码

layout = [ [sg.Text('???')],
           [sg.Text('???')],
           [sg.Text('???', sg.Button('???'))],
           [sg.Text('???')],
           [sg.Text('???')] ]

window = sg.Window('???', layout)

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

错误原因

  1. 布局结构错误:第三行sg.Text('???', sg.Button('???'))写法违规,PySimpleGUI要求每个界面组件都是布局列表中的独立元素,你把Button作为Text的第二个参数传递,导致Text组件的size参数被错误赋值为Button对象,渲染时触发解包错误。
  2. 后续尝试的event = window.read和values = window.read是无效修改:window.read()是方法调用必须加括号,且它返回(event, values)元组,需一次性解构赋值。

修复方案

  1. 修正布局:将Button从Text的参数中移出,作为同一行的独立元素。
  2. 完善窗口循环:添加关闭窗口的判断逻辑,避免无限循环。

修正后的完整代码:

import PySimpleGUI as sg

layout = [ [sg.Text('???')],
           [sg.Text('???')],
           [sg.Text('???'), sg.Button('???')],  # 修正为两个独立元素
           [sg.Text('???')],
           [sg.Text('???')] ]

window = sg.Window('???', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:  # 处理窗口关闭事件
        break

window.close()  # 关闭窗口释放资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:31