如何用PySimpleGUI在Python中动态生成嵌套按钮布局?
PySimpleGUI动态生成嵌套按钮布局报错解决方案
问题描述
我想用PySimpleGUI生成嵌套列表形式的菜单布局,目标结构是[[sg.Button('text1'), sg.Button('text2')], [sg.Button('text3')]],因为要根据列表大小动态生成按钮,不能硬编码。但现在代码生成了生成器对象,运行时触发AttributeError: 'generator' object has no attribute 'ParentContainer'错误,求修改代码解决。
当前代码
import PySimpleGUI as sg rows_needed = 2 result = [['text1', 'text2'], ['text3']] menu_layout = [] for x in range(0,rows_needed): temp = [] try: temp.append(sg.Button(c) for c in result[x]) finally: pass menu_layout.append(temp) print(menu_layout) layout = [[sg.Button(c) for c in result]] window = sg.Window('', menu_layout) window.read()
错误输出
[[<generator object menu.<locals>.<genexpr> at 0x0000016308733AE0>]] [[<generator object menu.<locals>.<genexpr> at 0x0000016308733AE0>], [<generator object menu.<locals>.<genexpr> at 0x0000016308733C30>]] Traceback (most recent call last): File "C:\Users\cafemax\projects\POS\POS\Client_Posv2.py", line 713, in <module> menu() File "C:\Users\cafemax\projects\POS\POS\Client_Posv2.py", line 532, in menu window = sg.Window('', menu_layout) File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9604, in __init__ self.Layout(layout) File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9783, in layout self.add_rows(new_rows) File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9753, in add_rows self.add_row(*row) File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9708, in add_row if element.ParentContainer is not None: AttributeError: 'generator' object has no attribute 'ParentContainer'
解决方案
问题根因
代码里temp.append(sg.Button(c) for c in result[x])这一行,把生成器对象直接塞进了temp列表,而不是生成实际的按钮元素列表。PySimpleGUI需要的是具体的UI元素实例(比如sg.Button),不是生成器,所以触发了属性错误。
修改后的代码
import PySimpleGUI as sg result = [['text1', 'text2'], ['text3']] # 用嵌套列表推导式直接生成目标布局,自动适配result的行数和每行元素数 menu_layout = [[sg.Button(c) for c in row] for row in result] window = sg.Window('', menu_layout) window.read() window.close() # 新增关闭窗口,避免资源泄漏
关键调整点
- 删掉冗余的
rows_needed变量和手动循环,直接遍历result的每一行,自动适配行数 - 把生成器表达式
(sg.Button(c) for c in result[x])改成列表推导式[sg.Button(c) for c in row],生成的是按钮实例的列表,而非生成器对象 - 移除无效的
layout = [[sg.Button(c) for c in result]]代码 - 添加
window.close()释放窗口资源
内容的提问来源于stack exchange,提问作者Physcofury
相关产品推荐
相关产品推荐

