pythonuser-interfacewindowpysimplegui

Duplicating window when pressing button


I'm trying to develop a script that would open a new window by clicking on the duplicate button and close it by clicking on close. I'm using the PySimpleGUI library. However, I encounter several errors.

Here is my script:

import PySimpleGUI as sg
n = 0
layout = [[sg.Text("Duplicate or close?")], [sg.Button("close")], [sg.Button("duplicate")]]
print(n)
# Create the window
window = sg.Window("Demo", layout)

# Create an event loop
while True:
    event, values = window.read()
    # End program if user closes window or
    # presses the OK button
    if event == "close" or event == sg.WIN_CLOSED:
        window.close()
        
    if event == "duplicate" or event == sg.WIN_CLOSED:
        n = [[sg.Text("Duplicate or close?")], [sg.Button("close")], [sg.Button("duplicate")]]
        window = sg.Window("Demo", n)
        n += 1

I'm getting this error:

Traceback (most recent call last):
File "/Users/GeliMorto/Documents/gui.py", line 19, in
n += 1

TypeError: 'int' object is not iterable

I've tried to make it whit an unique window layout:

import PySimpleGUI as sg
n = 0
layout = [[sg.Text("Duplicate or close?")], [sg.Button("close")], [sg.Button("duplicate")]]

But that did not work, either.

So I have done that at every loop the layout name changes. And I get the error I have shown above.


Solution

  • After following statement, n will be a List, how can it n += 1 ? Maybe replace it with different variable name, like layout.

    n = [[sg.Text("Duplicate or close?")], [sg.Button("close")], [sg.Button("duplicate")]]
    

    There's still issue about how you to close any opened window ? You didn't save all the old windows to do any action in the future , like close the window.

    Example Code

    import PySimpleGUI as sg
    
    def new_window(index):
        layout = [[sg.Text("duplicate or close?"), sg.Button("close"), sg.Button("duplicate"), sg.Button('close all')]]
        return sg.Window(f'Window #{index}', layout)
    
    window = new_window(0)
    windows = [window]
    index = 0
    
    while True:
    
        event, values = window.read()
    
        if event in (sg.WINDOW_CLOSED, 'close'):
            window.close()
            del windows[-1]
            index -= 1
            if windows:
                window = windows[-1]
                window.un_hide()
            else:
                break
    
        elif event == 'duplicate':
            window.hide()
            index += 1
            window = new_window(index)
            windows.append(window)
    
        elif event == 'close all':
            for window in windows:
                window.close()
            break