2

I have a program that has an sg.Output element, and I want a function to run after the window has opened/initialized.

This is a sample of my code:

import PySimpleGUI as sg
import os

layout = [[sg.Output(size=(50, 10))]]

window = sg.Window('SampleCode', layout)

def printAfter():
  print('Hello')

while True:
  event, values = window.read()
  
  printAfter()

  if event == sg.WIN_CLOSED:
    break

Problem is it seems to print it before it could initialize the window.

SappyCS
  • 53
  • 5
  • usually GUI runs some code only when you click button or select option - and it executes assigned function. And if you need some code all time then you may need to run in separated thread (and start this thread before `while True`. And some GUIs may have some `timer` to execute code with delay and then you may run some code little after GUI initialization. – furas Mar 23 '22 at 00:32
  • problem can be because `read()` wait for events like `button` click, etc - so it blocks loop - and it never execute `printAfter()` – furas Mar 23 '22 at 00:37
  • if you use `window.read(False)` then it will not block loop and it will run `printAfter()` again and again. – furas Mar 23 '22 at 00:40
  • huh, is there a way to make it run only once then? – SappyCS Mar 23 '22 at 02:03

1 Answers1

5

Option finalize=True in Window to let the GUI finalized, then you can run any code about GUI or after GUI initialized.

Method Window.read will wait event from GUI, so it do nothing before any event, like click the button.

Code in While condition loop will be executed repeatedly until the condition is False or break statement.

import PySimpleGUI as sg
import os

def printAfter():
  print('Hello')

layout = [[sg.Output(size=(50, 10))]]
window = sg.Window('SampleCode', layout, finalize=True)

printAfter()

while True:
  event, values = window.read()
  if event == sg.WIN_CLOSED:
    break

window.close()
Jason Yang
  • 11,284
  • 2
  • 9
  • 23