Joe Cz
Joe Cz

Reputation: 3

PySimpleGUI nonblocking popup that closes via message from main program or button click

I would like to learn the best way to make a popup window in the PySimpleGUI Python framework, that is a nonblocking popup (separate thread) and that can be closed either by the user clicking the Cancel button on the popup window OR by the main program sending a "close" command to the popup thread. Thanks very much. - Joe

I've used PySimpleGUI's sg.popup() function and am familiar with basic customizing using its parameters.

Upvotes: 0

Views: 463

Answers (1)

Jason Yang
Jason Yang

Reputation: 13051

Need to create the popup window by yourself, then you can add code how you to close which one popup window by button click.

from random import randint
import PySimpleGUI as sg

def new_window(index):
    w, h = sg.Window.get_screen_size()
    location = (randint(500, w-500), randint(200, h-200))
    layout = [[sg.Text(f'This is sub-window {index}', key='TEXT')], [sg.Button('OK')]]
    return sg.Window(f'Window {index}', layout, location=location, no_titlebar=True, finalize=True)

layout = [[sg.Button('New Window')]]
main_window = sg.Window('Main Window', layout=layout, finalize=True)
windows = [main_window]
index = 0
while True:

    win, event, values = sg.read_all_windows()

    if event in (sg.WINDOW_CLOSED, 'OK'):
        if win == main_window:
            break
        win.close()
        windows.remove(win)
        index -= 1
        for i, w in enumerate(windows[1:]):
            w['TEXT'].update(f'This is sub-window {i+1}')

    elif event == 'New Window':
        index += 1
        new_win = new_window(index)
        windows.append(new_win)
        main_window.force_focus()

for win in windows:
    win.close()

enter image description here

Upvotes: 2

Related Questions