Python PYserial WxPython线程

时间:2016-08-24 20:37:34

标签: python multithreading wxpython pyserial

任何人都可以告诉我这段代码有什么问题。

当我按下按钮1时 - 一切都很好。我想按下button2 - 停止按钮1启动的进程并执行另一个进程。我无法做到 - 我的GUI反应迟钝。

如果您喜欢doit和doit2函数,欢迎您使用PRINT语句编辑串行通信。

请不要评论我是如何制作GUI的 - 这只是一个简单的例子。请评论为什么我无法通过pill2kill - 当我按下按钮2.以及为什么我的GUI会处于无法响应的状态。

import threading
import time
import numpy as np
import serial
from Transmit import Write
from Receive import Read
import struct
import time
import serial.tools.list_ports


import wx







class windowClass(wx.Frame):
def __init__(self, parent, title):

    appSize_x = 1100
    appSize_y = 800

    super(windowClass, self).__init__(parent, title = title, style = wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CLOSE_BOX |wx.CAPTION, size = (appSize_x, appSize_y))

    self.basicGUI()
    self.Centre()
    self.Show()

def basicGUI(self):


    # Main Panel
    panel1 = wx.Panel(self)

    panel1.SetBackgroundColour('#D3D3D3')

    firmware_version = wx.StaticText(panel1, -1, "RANDOM1", pos = (70, 10) )

    firmware_version_text_control = wx.TextCtrl(panel1, -1, size = (70,25), pos = (105,40))

    pump_model_serial_number = wx.StaticText(panel1, -1, "RANDOM2", pos=(25, 75))
    pump_model_serial_number.SetBackgroundColour('yellow')

    model = wx.StaticText(panel1, -1, "RANDOM3", pos=(110, 100))

    self.listbox = wx.ListBox(panel1, -1, size = (300,250), pos = (20,135))

    clear_history = wx.Button(panel1, -1, 'BUTTON1', size = (225,30), pos = (40, 400))
    clear_history.SetBackgroundColour('RED')
    clear_history.Bind(wx.EVT_BUTTON, self.OnClearHistory)

    clear_history2 = wx.Button(panel1, -1, 'BUTTON2', size=(225, 30), pos=(40, 500))
    clear_history2.SetBackgroundColour('GREEN')
    clear_history2.Bind(wx.EVT_BUTTON, self.OnClearHistory2)



def OnClearHistory(self, event):

    self.pill2kill = threading.Event()
    self.t = threading.Thread(target=self.doit, args=(self.pill2kill, "task"))
    self.t.start()
    self.t.join()

def OnClearHistory2(self, event):

    self.pill2kill.set()

    self.t1 = threading.Thread(target=self.doit2)
    self.t1.start()
    time.sleep(5)
    self.t1.join()


def doit(self, stop_event, arg):

    while not stop_event.wait(1):
        print ("working on %s" % arg)

        ser = serial.Serial(3, 115200)
        c = ser.write('\x5A\x03\x02\x02\x02\x09')
        print c
        d = ser.read(7)
        print d.encode('hex')
        ser.close()


    print("Stopping as you wish.")


def doit2(self):
    #print ("working on %s" % arg)

    ser = serial.Serial(3, 115200)
    c = ser.write('\x5A\x03\x02\x08\x02\x0F') # Writing to an MCU
    print c
    d = ser.read(7)
    print d.encode('hex')
    ser.close()




def random():
    app = wx.App()
    windowClass(None, title='random')
    app.MainLoop()

random()

2 个答案:

答案 0 :(得分:1)

不要使用.join命令。他们阻止了主线 请参阅此SO问题以获得深入的描述:
what is the use of join() in python threading

答案 1 :(得分:1)

Thread.join将阻塞,直到线程终止。如果GUI的事件处理程序被阻止且无法返回MainLoop,则无法接收和分派其他事件,因此应用程序似乎被冻结。