0

I need an "add new group of controls" feature to a control panel built with PySimpleGUI. One selects which kind of group of controls each time, so it can't be predefined similarly to what is described in this answer to How to display different layouts based on button clicks in PySimple GUI? (Persistent window loop)

For brevity I've abstracted the problem here all the way down to a button that should add another slider each time it is pushed.

I've tried to update using window.Layout but this is rejected because it reuses existing objects. I tried a copy.deepcopy but that fails as well.

Is there a way to dynamically add a new group of controls (multiple times) specified by selecting from a list of options?

button should add another slider


import PySimpleGUI as sg

s = {'range': (2,6), 'resolution': 0.2, 'default_value': 5,
     'size': (20,15), 'orientation': 'horizontal',
     'font': ('Helvetica', 8), 'enable_events': True}

layout = [[sg.Slider(**s, key='hi'), sg.Button('Add Slider')]]

window = sg.Window('wow!', layout=layout, background_color="gray",
                   size=(400, 200)) 

while True:
    event, values = window.read()
    if event is None:
        break
    print(event, values)
    if event == 'Add Slider':
        layout[0][0].Update(value=8.0 - values['hi'])
        layout.append(sg.Slider(**s))
        window.layout(layout)

Error message:

# UserWarning: *** YOU ARE ATTEMPTING TO RESUSE AN ELEMENT IN YOUR LAYOUT! 
Once placed in a layout, an element cannot be used in another layout. ***`
uhoh
  • 3,713
  • 6
  • 42
  • 95

1 Answers1

1

Could you try using a function?

def Btn():
    return sg.Slider(**s)
layout.append(Btn())

Solution on Github

Banana
  • 2,295
  • 1
  • 8
  • 25
  • How would that help? – uhoh Mar 28 '20 at 18:41
  • 1
    I searched your Error and on github were people having the same issue. Someone wrote a function had helped him. I will add the link. – Banana Mar 29 '20 at 18:48
  • Oh that's great! Please ping me again when you do; I'm signing off now but I'll be back later. Thanks! – uhoh Mar 29 '20 at 18:54
  • @uhoh here's your ping – Banana Mar 29 '20 at 18:55
  • Thanks, I'm not sure that explanation is compatible where the effect of one control needs to be to *add more controls* to the layout as I'm trying to do here. It's hard to follow that thread because it spans a year and several versions, and I don't see where the final working code can be found. But I'll try some things along this line. – uhoh Mar 29 '20 at 23:45
  • The example script at the top of that thread doesn't run for other reasons as well. I have version 4.17 and I get `AttributeError: module 'PySimpleGUI' has no attribute 'GetPathBox'` that comment about the function was for version 4.4 and the script was written to run in 4.1 – uhoh Mar 29 '20 at 23:58