exiting a loop by pressing a escape key

微笑、不失礼 提交于 2019-12-12 11:08:36

问题


I am trying to exit a loop by pressing a escape key but my program doesn't work. Is there a way to do that? My code :

import win32api
import win32con
import time
from msvcrt import kbhit,getch

def clickerleft(x,y):
    """Clicks on given position x,y

    Input:
    x -- Horizontal position in pixels, starts from top-left position
    y -- Vertical position in pixels, start from top-left position

    """

    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)


def fonctionclic():
    while True :
        clickerleft(1193,757)
        time.sleep(0.1) 

while True :
    key = ord(getch())
    if key == 97: #a  
        fonctionclic()
    elif key == 27: #escap  
        break   

回答1:


It's not clear to me what you're trying to accomplish with the two while True: loops you have in your code, so I removed one of them thinking perhaps this does what you want:

import msvcrt
import win32api
import win32con
import time

def readch():
    """ Get a single character on Windows.

    see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=vs-2019
    """
    ch = msvcrt.getch()
    if ch in b'\x00\xe0':  # Arrow or function key prefix?
        ch = msvcrt.getch()  # Second call returns the actual key code.
    return ch

def clickerleft(x, y):
    """ Clicks on given x, y position.

    Input:
      x -- Horizontal position in pixels, starts from top-left position
      y -- Vertical position in pixels, start from top-left position
    """
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)

print('Press Esc to quit or "a" to simulate mouse click')
while True:
    if msvcrt.kbhit():
        key = ord(readch())
        if key == 97:  # ord('a')
            clickerleft(1193,757)
        elif key == 27:  # Escape key?
            break
    time.sleep(0.1)
print('Done')


来源:https://stackoverflow.com/questions/21653072/exiting-a-loop-by-pressing-a-escape-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!