为什么背景颜色改变需要这么长时间?

Why does it take so long for background color to change?

我 运行 遇到了一个简单程序的问题,该程序在通过 TCP 从另一台机器接收到命令时会更改背景颜色。改变颜色大约需要三十秒。我是 运行 通过本地网络发送的,因此它应该接近即时响应。我正在为框架使用 wxPython。我不认为我有过于复杂的代码。相关代码:

    threader=threading.Thread(target=self.threading)
    threader.start()
def threading(self):
    host="192.168.1.122"
    port=4100
    s=socket.socket()
    s.bind((host,port))
    s.listen(1)
    c,addr=s.accept()
    print "Connected"
    while 1:
        data=c.recv(1024)
        if not data:
            break
        data=data.split("_")
        reading=int(data[1])
        pin=int(data[0])
        if pin == 1:
            if reading<20:
                self.front_left.SetBackgroundColour("red")
        elif pin == 2:
            if reading<20:
                self.front_right.SetBackgroundColour("red")
        elif pin == 3:
            if reading<20:
                self.bottom_left.SetBackgroundColour("red")
        elif pin == 4:
            if reading<20:
                self.bottom_right.SetBackgroundColour("red")
        else:
            pass
    c.close()

我需要这个代码是即时的,因为这将在一个机器人上进行,它会判断物体是否太近(这就是为什么当它到达物体 20 厘米以内时会出现红色背景)。任何帮助将不胜感激!

您似乎正试图从线程更新 wxPython 代码。此操作在 wxPython 中不受支持/未定义。您需要使用线程安全的方法来更新 wxPython UI,例如 wx.CallAfter 或 wx.PostEvent。有关示例,请参见以下 wxPython wiki 页面:

基本上,您需要在 if 语句中执行类似的操作:

wx.CallAfter(self.bottom_right.SetBackgroundColour, "red")