Answer the question
In order to leave comments, you need to log in
How to stop a script after clicking a button?
I'm using the keyboard library to run the script, but it can't be used to close the script because if you write keyboard.wait("F3") it will wait for F3 and won't go any further. I have a system:
while True:
<...>
Answer the question
In order to leave comments, you need to log in
One way to solve the problem is to use multithreading. The created thread will handle keystrokes and signal this to the main one.
import keyboard
import threading
from time import sleep
def invert_event(key_event):
if start_event.is_set():
start_event.clear()
else:
start_event.set()
def listen_F3():
# при опущении зажатой кнопки f3
# меняем флаг события на противоположный
keyboard.on_release_key(key='F3', callback=invert_event)
# объект собития, с его помощью
# сигнализируем основной поток
# о нажатии клавиши
start_event = threading.Event()
# запускаем поток обработки нажатий
threading.Thread(target=listen_F3).run()
# ждем клавишу
start_event.wait()
while start_event.is_set():
print('processing...')
sleep(1)
print('script finished.')
while start_event.wait():
print('processing...')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question