'PySimpleGUI Window Disappearing too Quickly/Some Other Options Needed

I've created a PySimpleGUI Window with some text, a transparent background and no title bar, however it's not respecting the auto_close_duration property. I know it'll be because I'm not implementing it correctly, but just looking at how to fix that.

Also, I would like the window to stay alive for that amount of time before closing, but also to listen for any keyboard button press to auto close it early. If any keyboard button doesn't work, the Escape button could be used, but on ANY keyboard press is ideal.

This is what I have right now, it flashes the text before disappearing. Python 3.8+ Windows 10.

import PySimpleGUI as sg

def popup(message):

    # Set font options
    sg.set_options(font=("Courier New", 24))

    # Define the transparent bg colour
    bg = '#add123'

    # Define a layout with our message to display
    layout = [[sg.Text(message, background_color=bg, pad=(0, 0))]]

    # Get the width and height of the current monitor (to use later)
    w, h = sg.Window.get_screen_size()

    # Define a window object to show our layout
    win = sg.Window('title', layout,
                    no_titlebar=True,
                    keep_on_top=True,
                    location=(None, None),
                    auto_close=True,
                    auto_close_duration=20,
                    transparent_color=bg,
                    margins=(0, 0),
                    # finalize=True,
                    )

    # Read the window?
    event, values = win.read(timeout=0)

    # Attempts to keep window alive for the auto_close_duration
    win.force_focus()

    # 1. How to keep window/popup message visible for auto_close_duration?
    # 2. How to close window if ANY keyboard button pressed, or the Escape key at the least?

    # win.close()
    return

popup('Here is the message.')


Solution 1:[1]

Set two conditions to generate keyboard event to exit.

  • option return_keyboard_events=True in Window and
  • option timeout in method read of Window
import PySimpleGUI as sg

def popup(message):
    sg.set_options(font=("Courier New", 24))
    bg = '#add123'
    layout = [[sg.Text(message, background_color=bg, pad=(0, 0))]]
    win = sg.Window('title', layout, no_titlebar=True, keep_on_top=True,
        location=(1000, 200), transparent_color=bg, margins=(0, 0),
        return_keyboard_events=True)
    win.read(timeout=3000, close=True)
    return

popup('Here is the message.')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1