[英]How to exit a function because a key was pressed?
我試圖每三秒移動一次我的 Cursor,如果它走得太遠,請將其重置到原來的位置。 我希望程序在我按下鍵盤上的任意鍵后停止。
雖然它似乎不起作用......我會錯過什么? 這就是我想出的:
import win32api, win32con, time, sys, msvcrt
global z
z=10
def kbfunc():
#this is boolean for whether the keyboard has bene hit
x = msvcrt.kbhit()
if x:
sys.exit
else:
ret = False
return ret
def move(x,y):
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(x/1920*65535.0), int(y/1080*65535.0))
while True:
move(960,540+z)
time.sleep(3)
if z>100:
move(960,540)
z += -100
z + 10
kbfunc()
首先,您需要安裝鍵盤模塊:
pip3 install keyboard
而不是將其添加到您的循環中:
import keyboard
while True:
move(960,540+z)
time.sleep(3)
if z>100:
move(960,540)
z += -100
z + 10
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
我猜想msvcrt.kbhit()
不會存儲以前的命中。 它只告訴您是否在當前時刻按下了鍵。 您可以循環檢查鍵盤點擊。 如果 3 秒前沒有命中,則返回:
import time
import msvcrt
import sys
def kbfunc(max_time=3):
start = time.time()
while not msvcrt.kbhit():
end = time.time()
if end - start >= max_time:
break
else:
sys.exit()
在嘗試了給定的答案后,完成的解決方案如下所示:
global z
z=10
def move():
mouse.move(10, 10, absolute=False, duration=1)
def moveback():
mouse.move(-10, -10, absolute=False, duration=1)
while True:
move()
time.sleep(3)
moveback()
if keyboard.is_pressed('q'): # if key 'q' is pressed
break # finishing the loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.