David
David

Reputation: 1

How to make the time.sleep an input using PySimpleGUI

How can I make an input option where the value inputted is used to sleep and not the time in the code 'time.sleep(10)', for example I inputted 30 into the Psg.Input after i press on punch i want it to wait 30 seconds then break

import PySimpleGUI as Psg
import time
import pause
from pynput.keyboard import Key, Controller
loop = 0
cancel_loop = 0
punch_wait = 0
punch_time = 0
keyboard = Controller()
layout = [[Psg.Button("punch")],
          [Psg.Button("Close")]]
window = Psg.Window("App", size=(300, 270)).Layout(layout)
def cancel():
    if event == "Close":
        pass
def d_press():
    keyboard.press(Key.right)
    pause.milliseconds(punch_time)
    keyboard.release(Key.right)
    pause.milliseconds(punch_wait)
    keyboard.release(Key.space)
    return event
def space_press():
    keyboard.press(Key.space)
    pause.milliseconds(1)
def movement():
    d_press()
    space_press()
while True:
    event, values = window.read()
    if event == Psg.WIN_CLOSED:
        break
    if event == "Close":
        break
    if event == "punch":
        punch_wait = 300
        punch_time = 85
        loop = 1
    while loop == 1:
        movement()
        cancel()
        time.sleep(10)
        break

Upvotes: 0

Views: 944

Answers (1)

Jason Yang
Jason Yang

Reputation: 13051

Call time.sleep will block your code in the main thread and there maybe no response for your GUI.

Prefer to do it in other thread. Following code show the way to go.

from time import sleep
import threading
import PySimpleGUI as sg

def action(window, punch_time, wait_time):
    print("Key Pressed - Space")
    print("Key Pressed - Right")
    print(f"Wait {punch_time} seconds")
    sleep(punch_time)
    print("Key Released - Right")
    print(f"Wait {wait_time} seconds")
    sleep(wait_time)
    print("Key Released - Space")
    print("Thread finished\n")
    # Call window.write("EVENT", "VALUE") in thread to update GUI if required

layout = [
    [sg.Text("Punch time", size=10), sg.Input("", size=10, key='Punch Time')],
    [sg.Text("Wait time",  size=10), sg.Input("", size=10, key='Wait Time')],
    [sg.Button('Punch'), sg.Button('Exit')],
]

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

while True:

    event, values = window.read()

    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    elif event == 'Punch':
        try:
            punch_time, wait_time = float(values['Punch Time']), float(values['Wait Time'])
        except ValueError:
            print('Wrong value for time')
            continue
        threading.Thread(target=action, args=(window, punch_time, wait_time), daemon=True).start()
    elif event == 'EVENT':
        value = values[event]
        """ Update GUI here """

window.close()

Upvotes: 1

Related Questions