2014-02-08 181 views
2

我試圖通過按下退出鍵退出循環,但我的程序無法正常工作。有沒有辦法做到這一點? 我的代碼:按退出鍵退出循環

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 

回答

2

這不是我清楚你想與你在你的代碼有兩個while True循環來完成什麼—所以我刪除其中的一個心想也許這你想要做什麼:

import msvcrt 
import win32api 
import win32con 
import time 

def readch(): 
    """ Get a single character on Windows. 
    see http://msdn.microsoft.com/en-us/library/078sfkak 
    """ 
    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 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) 

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

感謝您的回答,但我該如何處理點擊功能中的while循環。 – user3144427

+0

查看更新的答案。請注意,在我的系統上,模擬點擊轉移焦點遠離我用來運行腳本的控制檯窗口。 – martineau