我在这里写了一个简短的程序来记录和回放我的鼠标动作。我已经实现了一个简单的 GUI,PyQt
并且过去可以使用它。最近我决定通过实现而不是在主循环QThread
中使用来更新代码以减少“hacky” 。processEvents()
下面的代码执行,但行为奇怪。运行代码时,会发生以下情况:
输入1:我按记录
控制台输出:
isRecording = True
输入 2:我按下停止
控制台输出:
Stopped!
输入 3:我按下播放
控制台输出:
isRecording = True
输入 4:我按下停止
控制台输出:
Stopped!
Play!
Playback complete!
我不清楚为什么按下play
程序后会尝试再次录制,并且只有在按下停止后才会开始播放。此外,在经历了这段怪异之后,它继续表现出这种类似类型的输出,但偏差很小。
我的猜测是它与重新分配线程信号started
有关,具体取决于我是否调用类的play
orrecord
成员函数CursorCapture
。
任何见解将不胜感激。
代码
import win32api
import sys
import time
from PyQt4 import QtGui
from PyQt4.QtCore import Qt, QPoint
from PyQt4 import QtCore
class MouseRecord(QtCore.QObject):
finished = QtCore.pyqtSignal()
def __init__(self):
super(MouseRecord, self).__init__()
self.isRecording = False
self.cursorPath = []
@QtCore.pyqtSlot()
def record(self):
self.isRecording = True
self.cursorPath = []
print "isRecording = " + str(self.isRecording)
while(self.isRecording):
#print "Recording"
self.cursorPath.append(win32api.GetCursorPos())
time.sleep(.02)
self.finished.emit()
print "Stopped!"
def stop(self):
self.isRecording = False
@QtCore.pyqtSlot()
def play(self):
print "Play!"
for pos in self.cursorPath:
#print "Playing"
win32api.SetCursorPos(pos)
time.sleep(.02)
print "Playback complete!"
self.finished.emit()
class CursorCapture(QtGui.QWidget):
def __init__(self):
super(CursorCapture, self).__init__()
self.isRecording = False
self.mouseRecorder = MouseRecord()
self.myThread = QtCore.QThread()
self.mouseRecorder.moveToThread(self.myThread)
self.mouseRecorder.finished.connect(self.myThread.quit)
self.initUI()
def initUI(self):
self.recordBtn = QtGui.QPushButton("&Record")
self.stopBtn = QtGui.QPushButton("&Stop")
self.playBtn = QtGui.QPushButton("&Play")
self.recordBtn.clicked.connect(self.record)
self.stopBtn.clicked.connect(self.stop)
self.playBtn.clicked.connect(self.play)
self.hBox = QtGui.QHBoxLayout()
self.hBox.addWidget(self.recordBtn)
self.hBox.addWidget(self.stopBtn)
self.hBox.addWidget(self.playBtn)
self.setLayout(self.hBox)
self.setWindowTitle("Cursor Capture")
self.show()
def record(self):
self.myThread.started.connect(self.mouseRecorder.record)
self.myThread.start()
def stop(self):
self.mouseRecorder.stop()
def play(self):
self.myThread.started.connect(self.mouseRecorder.play)
self.myThread.start()
def main():
qApp = QtGui.QApplication(sys.argv)
cursorCapture = CursorCapture()
sys.exit(qApp.exec_())
if __name__ == "__main__":
main()