Skip to main content
 首页 » 编程设计

python之WxPython PySerial 和 Wx.Terminal之线程无法更新 GUI

2024年09月07日53小虾米

之前的一些东西:

这里都是基于wxTerminal.py Link

(Pyserial 微型端口和 WxPython GUI 的组合)

使用: python :2.7.14。 WxPython:4.0.0b2

我的问题是我有一个线程从我的设备读取串行数据, 并尝试使用事件更新 GUI:

class TerminalFrame(wx.Frame): 
    .... 
    .... 
    def ComPortThread(self): 
        """\ 
        Thread that handles the incoming traffic. Does the basic input 
        transformation (newlines) and generates an SerialRxEvent 
        """ 
        while self.alive.isSet(): 
            b = self.serial.read(self.serial.in_waiting or 1) 
            if b: 
                # newline transformation 
                if self.settings.newline == NEWLINE_CR: 
                    b = b.replace(b'\r', b'\n') 
                elif self.settings.newline == NEWLINE_LF: 
                    pass 
                elif self.settings.newline == NEWLINE_CRLF: 
                    b = b.replace(b'\r\n', b'\n') 
                event = SerialRxEvent(self.GetId(), b) 
 **ERROR!** >>> self.GetEventHandler().AddPendingEvent(event) 

我得到一个错误:

File "C:/Users/DIMA/Desktop/pyserial-master/pyserial-master/examples/wxTerminal.py", line 349, in ComPortThread 
    self.GetEventHandler().AddPendingEvent(event) 
wxAssertionError: C++ assertion "event" failed at ..\..\src\common\event.cpp(1246) in wxEvtHandler::QueueEvent(): NULL event can't be posted 

缺少什么?

    SERIALRX = wx.NewEventType() 
    # bind to serial data receive events 
    EVT_SERIALRX = wx.PyEventBinder(SERIALRX, 0) 
 
 
class SerialRxEvent(wx.PyCommandEvent): 
    eventType = SERIALRX 
 
    def __init__(self, windowID, data): 
        wx.PyCommandEvent.__init__(self, self.eventType, windowID) 
        self.data = data 
 
    def Clone(self): 
        self.__class__(self.GetId(), self.data) 

请您参考如下方法:

这也是我曾经困惑过的事情。

由于某些原因,Clone 方法永远不会在 wxPython classic 中被调用(尝试插入 raise)。而 pyserial 作者似乎弄错了那个。根据the docs Clone 方法应返回一个新事件!

当使用 Phoenix(通过 pip 安装获得的那个)时,将调用 Clone 方法。因为您返回 None,AddPendingEvent 会提示。

在事件类(wxTerminal 中的 SerialRxEvent)中编辑 Clone 方法,使其正确返回:

def Clone(self): 
    # raise # uncomment this to show that this will not get called in classic 
    # instead of this 
    # self.__class__(self.GetId(), self.data) 
    # do this 
    return self.__class__(self.GetId(), self.data)