2016-08-24 76 views
1

任何人都可以告訴我這段代碼有什麼問題。Python PYserial WxPython線程

當我按下按鈕1 - 一切都很好。我想按下按鈕2 - 停止按鈕1啓動的過程並執行另一個過程。我無法做到 - 我的圖形界面無反應。

如果您喜歡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() 

回答

1

Thread.join將阻塞,直到線程終止。如果您的GUI事件處理程序被阻止並且無法返回到MainLoop,則其他事件將無法接收和分派,因此應用程序似乎被凍結。