import pyautogui
import time
import PySimpleGUI as sg
def main_app():
try:
layout = [[sg.Text('Enter the number of clicks to perform: '), sg.InputText()],
[sg.Text('Enter the interval between messages (in seconds): '), sg.InputText()],
[sg.Button('Start'), sg.Button('Stop')]]
window = sg.Window('Automatic Clicker', layout)
while True:
event, values = window.read()
if event == 'Start':
num_clicks = int(values[0])
type_interval = float(values[1])
time.sleep(5)
for i in range(num_clicks):
pyautogui.click()
time.sleep(10)
pyautogui.typewrite("Hello, wORLD how are you", interval=5)
pyautogui.press('enter')
time.sleep(type_interval)
time.sleep(5)
if event == 'Stop' or event == sg.WINDOW_CLOSED:
break
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
window.close()
if __name__ == "__main__":
main_app()
I'm trying to use pysimplegui for creating GUI application,This application is very simple it has 2 buttons start, stop and two input fields where first field takes input to how may times "HELLO World How are you" should be printed. Second input defines delays between printing letters, So when start is given it starts to print the given sentence , but while pressing stop it doesn't stops. instead i have to kill the application from the terminal , how do i make the application stop by pressing stop button
A thread, as Jason's answer shows quite well, is usually the best way to handle these kinds of long operations. I decided to try a slightly different approach. Because so much of your time is simply sleeping, I thought maybe you could get away with using timers to control the flow.
The problem you're running into is that during the time you're sleeping, everything's stopped. The GUI, responding to your input, etc.... it's all stopped.
Using the PySimpleGUI Timer API you can run the timer in the background and continue to perform actions in your GUI.
The implementation is overkill in the use of
write_event_value
. This is so that the code could be moved into a thread and then the thread would communicate with the GUI using the samewrite_event_value
call.The Timer API calls are not yet released on PyPI, so you'll have to get the latest PySimpleGUI from GitHub. This code will be released to PyPI very soon (by the end of the month or sooner).