是的。GUI 编程的关键是永远不要在主线程上进行任何长时间的操作,因为它会阻塞整个程序,直到该操作完成。
如果您想通过网络连续发送数据,请在后台线程中进行。
为您提供一些示例代码。
class MessageWorker(QtCore.QThread):
def __init__(self):
super(ParserWorker, self).__init__()
self.ok_to_send = False
self.terminated = True
def run(self):
while not self.terminated:
if self.ok_to_send:
self.send_message()
time.sleep(1)
def start_send():
self.ok_to_send = True
def pause_send():
self.ok_to_send = False
def terminated():
self.terminated = False
然后在主程序中调用
worker = MessageWorker()
worker.start() # Start the background thread
worker.start_send() # Start sending message
worker.pause_send() # Pause sending message
worker.terminated() # Stop sending message permanently