我正在創(chuàng)建一個(gè)腳本,在該腳本中,如果用戶按f7鍵,它將開(kāi)始記錄鼠標(biāo)的點(diǎn)擊,而當(dāng)他釋放按鈕時(shí),它應(yīng)該停止,除非用戶關(guān)閉程序,否則這種情況會(huì)發(fā)生。我編寫(xiě)了一個(gè)代碼,該代碼在按f7鍵時(shí)開(kāi)始記錄鍵,但是放開(kāi)它仍會(huì)記錄該鍵,這也是因?yàn)殒I處于連續(xù)按下位置,它會(huì)繼續(xù)啟動(dòng)多個(gè)偵聽(tīng)器,并且數(shù)據(jù)會(huì)變得越來(lái)越多余。同樣在釋放f7之后,監(jiān)聽(tīng)器不會(huì)停止這是代碼from pynput import mouse, keyboardfrom pynput.keyboard import Key, Listenerimport picklex_pos = []y_pos = []both_pos = []file = open("test.txt", "wb")file.close()def on_press(key): mouse_listener = mouse.Listener(on_click=on_click) if (key==keyboard.Key.f7): mouse_listener.start() print("done")def on_release(key): if (key==keyboard.Key.f7): mouse_listener.stop() print("closing file") #file.close()def on_click(x, y, button, pressed): if pressed: print ("{0} {1}".format(x,y)) x_pos.append("{0}".format(x,y)) y_pos.append("{1}".format(x,y)) #print (x_pos) #print (y_pos) both_pos = x_pos, y_pos with open("temp.txt", "ab") as file: pickle.dump(both_pos, file) print(both_pos)mouse_listener = mouse.Listener(on_click=on_click)#mouse_listener.start()with keyboard.Listener(on_press = on_press, on_release = on_release) as listener: try: #listener.start() listener.join() except MyException as e: print('Done'.format(e.args[0]))
1 回答

侃侃無(wú)極
TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
您mouse_listener在on_release和中沒(méi)有相同的引用on_press。
取出mouse_listener = mouse.Listener(on_click=on_click)在on_press和界定mouse_listener既之前on_press和on_release
mouse_listener = mouse.Listener(on_click=on_click)
def on_press():
# do on press stuff with mouse_listener
pass
def on_release():
# do on release stuff with mouse_listener
pass
將整個(gè)內(nèi)容包裝在一個(gè)類中可能也值得
添加回答
舉報(bào)
0/150
提交
取消