Run code after the window has been initialized - python

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.

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()

Related

Python - Opening a dialog box on key press

I want to open a dialog box (that captures an input string from the user) when the user clicks a keyboard button. I'm using "tkinter" for the dialog box, and "pynput" for capturing keystrokes.
The dialog box works ok, if I'm placing the "simpledialog" command on the main code section. I fail to find a way to make it work only when I'm clicking a button (F2 in the following example):
import time # For the delay function
from pynput import keyboard # For catching keyboard strokes
import tkinter
from tkinter import simpledialog
# Execute functions based on the clicked key
def on_press(key):
if key == keyboard.Key.f2:
USER_INP = simpledialog.askstring(title="Test", prompt="What's your Name?:")
ROOT = tkinter.Tk()
ROOT.withdraw() # Hides tkinter's default canvas
# Assigning event to function
listener = keyboard.Listener(on_press=on_press)
# initiating listener
listener.start()
while 1 < 2:
time.sleep(.01)
Can anyone help?
Thanks
Ok, in the meantime, I've solved it by doing two things:
Moving the "simpledialog" back to the main code section (inside a while loop)
Using a global variable to indicate whether I should open the dialog box.
import time # For the delay function
from pynput import keyboard # For catching keyboard strokes
import tkinter
from tkinter import simpledialog
openBox = False
# Execute functions based on the clicked key
def on_press(key):
global openBox
if key == keyboard.Key.f2:
openBox = True
ROOT = tkinter.Tk()
ROOT.withdraw() # Hides tkinter's default canvas
# Assigning event to function
listener = keyboard.Listener(on_press=on_press)
# initiating listener
listener.start()
while 1 < 2:
if openBox:
USER_INP = simpledialog.askstring(title="Test", prompt="What's your Name?:")
print(USER_INP)
openBox = False
time.sleep(.01)

Code for buttons or text not working with PySimpleGui

import PySimpleGUI as sg
layout = [[sg.Text("Placeholder")], [sg.Button("OK")]]
window = sg.Window('Window Title', layout, location=(0,0), size=(1000,700), keep_on_top=True)
while True:
event, values = window.read()
if event == "OK" or event == sg.WIN_CLOSED:
break
I am new to GUI programming. I tried to use this code to create a simple window with a button but when I do, I only get a blank screen without buttons or text.

Python subprocess.run() not responding on PySimpleGUI

When I run the sample code below and click on the button, the GUI window shows not responding? Maybe because The GUI is waiting for the subprocess.run() to finish, because when I close the browser that is opened by the GUI, it is not responding anymore. How can I use the GUI when using subprocess.run()? Thanks.
Here is my sample code:
import PySimpleGUI as sg
import subprocess
layout = [
[sg.Button('Open Browser', key="ob")]
]
window = sg.Window('Metamask Accounts Opener', layout, element_justification='c', size=(400, 400))
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit': # if user closes window or clicks cancel
break
if event == "ob":
subprocess.run('"C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe" --remote-debugging-port=9222 -- "%1"')
window.close()
subprocess.run waits for the process to finish. You need to use Popen in order to not wait and just run in the background.
Popen(['"C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe"' ,"--remote-debugging-port=9222","--","%1"])

Force overlay a PySimpleGUI window

I just want that if someone tries to close the GUI window using close button instead of clicking "OK", the window reappears... In simple words, they cannot close this one or access any other window without clicking "OK".
import PySimpleGUI as sg
layout = [[sg.Text("Click OK to start the unlock process using Face Verification")],
[sg.Button("OK")]]
# 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 == "OK" or event == sg.WIN_CLOSED:
break
window.close()
It is defined in source code of PySimpleGUI.
You can change it to generate an event "WIN_CLOSE", like this
import PySimpleGUI as sg
layout = [[sg.Text("Click OK to start the unlock process using Face Verification")], [sg.Button("OK")]]
window = sg.Window("Title", layout, finalize=True)
window.TKroot.protocol("WM_DESTROY_WINDOW", lambda:window.write_event_value("WIN_CLOSE", ()))
window.TKroot.protocol("WM_DELETE_WINDOW", lambda:window.write_event_value("WIN_CLOSE", ()))
while True:
event, values = window.read()
print(event)
if event in ("OK", sg.WIN_CLOSED):
break
elif event == "WIN_CLOSE":
print("Close Button 'X' clicked !")
window.close()
WIN_CLOSE
Close Button 'X' clicked !
WIN_CLOSE
Close Button 'X' clicked !
WIN_CLOSE
Close Button 'X' clicked !
OK

Detect cancel events of FileBrowse in PySimpleGUI

I am trying to build a user interface using PySimpleGui. Below is a minimal example of a file browser button. If you click on the button, it opens an Open file dialog.
import PySimpleGUI as sg
file_browse_button = sg.FileBrowse(enable_events=True)
layout = [[file_browse_button]]
window = sg.Window('My window', layout)
while True:
event, values = window.read()
print(event, '##', values)
if event is None or event == 'Cancel':
break
window.close()
When selecting a file, this produces (for example):
Browse ## {'Browse': '/path/to/file.txt'}
The problem is that if the user selects "Cancel" or just the previously selected file in the browser window, it will still produce the same event, not changing the value. Is there a way to differentiate the two cases?
My understanding is that the FileBrowse button best operates with its target parameter. That's how I use it anyway. The target parameter is the key for another PySimpleGUI element in the window where the button will store its value when the user clicks "ok". If the user clicks "Cancel" in the FileBrowse button, any selected value will not be inserted into the target.
import PySimpleGUI as sg
file_browse_button = sg.FileBrowse(target='filebrowse_field')
filebrowse_field = sg.Input(key='filebrowse_field')
ok_cancel = [ [sg.Button('OK'), sg.Button('Cancel')]]
layout = [[filebrowse_field, file_browse_button],
ok_cancel]
window = sg.Window('My window', layout)
while True:
event, values = window.read()
print(event, '##', values)
if event is None or event == 'Cancel':
break
window.close()
Note also that I don't have the enable-events option set for the FileBrowse element. I believe the intention is that your window has in it ok, cancel button to manage those events explicitly.

Categories

Resources