gpt4 book ai didi

Python 实时鼠标数据与 pyqtgraph

转载 作者:行者123 更新时间:2023-12-01 04:52:48 30 4
gpt4 key购买 nike

在我的 ubuntu (14.04) 操作系统上使用 python 处理原始鼠标数据的史诗般的斗争中,在这里的大量帮助下我再次陷入困境。我似乎很难理解 pyqtgraph 的“简单性”。我想做的就是将我现在拥有的代码包装到一个漂亮的小图形用户界面中,其中包含一个开始/暂停/停止按钮、一个显示数字的列表小部件和一个让我看到发生了什么的图。我想我的主要问题是,我不太理解 pyqt 中的整个事件。无论如何,采用一个包含我想要的小部件的“简单”示例,我无法实现我的代码(编辑得更简约):

#!/usr/bin/python
import threading
import struct
import time
import numpy as np

from PyQt4 import QtGui # (the example applies equally well to PySide)
from PyQt4 import QtCore
import pyqtgraph as pg
##
data =[(0,0)]
sum_data = [(0,0)]
file = open("/dev/input/mouse2", "rb")

def getMouseEvent():
buf = file.read(3);
#python 2 & 3 compatibility
button = buf[0] if isinstance(buf[0], int) else ord(buf[0])
x,y = struct.unpack( "bb", buf[1:] );
print x,y
return x, y

def mouseCollect():
while True:
data.append(getMouseEvent())
sum_data.append(tuple(map(sum,zip(sum_data[-1],data[-1]))))
plot.plot(sum_data[0], clear=True)
pg.QtGui.QApplication.processEvents()
print sum_data[-1]

## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])

## Define a top-level widget to hold everything
w = QtGui.QWidget()

## Create some widgets to be placed inside
btn1 = QtGui.QPushButton('Start')

listw = QtGui.QListWidget()
plot = pg.PlotWidget()

def start_btn():
print 'test'
threading.Thread(target=mouseCollect).start()

btn1.clicked.connect(start_btn)

## Create a grid layout to manage the widgets size and position
layout = QtGui.QGridLayout()
w.setLayout(layout)
## Add widgets to the layout in their proper positions
layout.addWidget(btn1, 0, 0) # button goes in upper-left
layout.addWidget(plot, 0, 1, 4, 1)
## Display the widget as a new window
w.show()
## Start the Qt event loop
app.exec_()
##------------------------------------------------------------------

当我按下开始按钮时,窗口就卡住了,什么也没有发生。我的想法是,如果我按下按钮,它就会连接到那里的方法状态,并且它只是做它的事情。好吧,我有一个无限循环,但至少我认为我应该看到一些东西。感谢任何帮助,也非常欢迎任何有关阅读此事的建议。

问候编辑:按照 echocage 的建议插入一个线程

最佳答案

重复更新的最佳方法是使用 QTimer。通过这种方式,您允许程序控制在每次更新后返回到 Qt 事件循环(不允许无限循环),并且 Qt 定期为您调用更新函数。

例如,请参阅 pyqtgraph 中包含的众多更新绘图示例之一:https://github.com/pyqtgraph/pyqtgraph/blob/develop/examples/Plotting.py#L58

线程很难正确执行,如果执行错误,通常会导致难以调试的崩溃。我建议避免使用线程,直到您对事件系统非常有信心并熟悉线程的陷阱。

关于Python 实时鼠标数据与 pyqtgraph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075205/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com