Home > front end >  is it possible to add code to a list in python
is it possible to add code to a list in python

Time:08-24

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()

so im attempting to create a nested list for menu layout, the result i want would be for example

menu_layout = [[sg.Button('text1'), sg.Button('text2')], [sg.Button('text3')],]

im using pysimplegui

my current code at the top gives the following result in powershell

[[<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'

the reason im trying to do this is because i need to be able to generate a variable amount of buttons based on the size of a list so i can't hard code this.

any help on how to fix this or change must make to my append

CodePudding user response:

temp doesn't contain sg.Button objects, it contains generators because that's what you appended to it. You don't want to create temp and then append the generator to it, you want to extend your list with your generator. See What is the difference between Python's list methods append and extend?

for x in range(0, rows_needed):
    temp = []
    try:
        temp.extend(sg.Button(c) for c in result[x])
    finally:
        pass
    menu_layout.append(temp)

Alternatively, you can simply create temp using a list comprehension:

for x in range(0, rows_needed):
    temp = []
    try:
        temp = [sg.Button(c) for c in result[x]]
    finally:
        pass
    menu_layout.append(temp)

I'm not sure what the try..finally is for, it doesn't seem to be doing anything, but I left it in because that's not the question you're asking.

  • Related