[英]Using a key listener to stop a loop
我試圖讓 python 運行一個循環,當我按Shift+a時循環停止:
import pyautogui
import time
import random
from pynput.mouse import Button, Controller
from pynput import keyboard
COMBINATIONS =[
{keyboard.Key.shift, keyboard.KeyCode(char='a')},
{keyboard.Key.shift, keyboard.KeyCode(char='A')}
]
on = True
print(on)
mouse = Controller()
curent = set()
def execute():
on = False
pass
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
curent.add(key)
if any(all(k in curent for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
curent.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listner:
listner.join()
execute()
time.sleep(4)
while on == True:
print('hi')
問題是代碼甚至沒有到達:
with keyboard.Listener(on_press=on_press, on_release=on_release) as listner:
listner.join()
如果我把它放在while True
循環之后,快捷方式不起作用,它就會停止,如果我把它放在while True
循環中,它會暫停循環。
您可以簡單地使用 add_hotkey 方法。 這是一個例子:
import keyboard
on = True
def execute():
on = False # The function you want to execute to stop the loop
keyboard.add_hotkey("shift+a", execute) # add the hotkey
while on:
print("hi") # Do the code of your loop here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.