class MyClass:
# This method will run on a separate thread
def _serial_port_worker(self):
while self._run_worker:
self.send_data_to_serial_port()
time.sleep(1)
# Call this to start the worker thread
def start_worker_thread(self):
self._run_worker = True
worker_thread = threading.Thread(target=self._serial_port_worker,
args=(self,))
worker_thread.start()
# Call this to tell the worker thread to stop
def stop_worker_thread(self):
self._run_worker = False
要看情况。。。如果发送操作很快,可以使用QTimer类。它与Qt事件循环集成,因此您不必担心线程问题。串行通信可能会很慢,这取决于您发送的数据量,所以我不能确定这是否是适合您的解决方案。在
是的,你需要使用线程。在任何基于GUI的程序中,任何需要花费大量时间的工作都应该在单独的线程上进行,以避免在看到“无响应”程序时阻塞UI,这几乎总是由于程序无法处理窗口消息,因为它的UI线程在一些长时间操作中被阻塞。在
启动后台线程的一个简单方法是使用^{} module 。下面是如何使用它每秒向串行端口写入一次数据:
是的。GUI编程的关键是永远不要在主线程上执行任何长操作,因为它会阻塞整个程序,直到该操作完成为止。在
若您想通过网络连续发送数据,请在后台线程中执行。在
为您提供一些示例代码。在
然后在主程序中调用
^{pr2}$相关问题 更多 >
编程相关推荐