【问题标题】:exiting a loop by pressing a escape key按退出键退出循环
【发布时间】:2014-02-08 23:26:49
【问题描述】:

我试图通过按转义键退出循环,但我的程序不起作用。有没有办法做到这一点? 我的代码:

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   

【问题讨论】:

    标签: python python-3.x windows pywin32 msvcrt


    【解决方案1】:

    我不清楚你想用代码中的两个 while True: 循环来完成什么,所以我删除了其中一个,认为这可能是你想要的:

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

    【讨论】:

    • 感谢您的回答,但如何在点击功能中使用 while 循环。
    • 查看更新的答案。请注意,在我的系统上,模拟点击会将焦点从我用来运行脚本的控制台窗口转移。