简体   繁体   English

由于按下了一个键,如何退出 function?

[英]How to exit a function because a key was pressed?

Im trying to move my Cursor every three seconds and if it went too far, reset it to its original location.我试图每三秒移动一次我的 Cursor,如果它走得太远,请将其重置到原来的位置。 I want the program to stop after I press any key on the keyboard.我希望程序在我按下键盘上的任意键后停止。

It doesnt seem to work though... what could I be missing?虽然它似乎不起作用......我会错过什么? This is what I came up with:这就是我想出的:

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() 

First, you need to install the keyboard module:首先,您需要安装键盘模块:

pip3 install keyboard

And than add it to your loop:而不是将其添加到您的循环中:

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

I would guess that msvcrt.kbhit() does not store previous hits.我猜想msvcrt.kbhit()不会存储以前的命中。 It only tells you if a key is hit at the current moment in time.它只告诉您是否在当前时刻按下了键。 You can loop checking for keyboard hits.您可以循环检查键盘点击。 If no hits before 3 seconds, return:如果 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()

After trying around with the given answers, the finished solution looks like this:在尝试了给定的答案后,完成的解决方案如下所示:


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM