Alright, the way it was is not ok, the thread was left alive continually sending updates to a GUI that didn't exist. This caused it to throw a nasty error about the C++ bit not being real or some such nonsense. But you can avoid this pretty easily by making the following changes:
- Create the thread within the GUI's
__init__()
method and create it as a class attribute - Have the
closeWindow()
method of your GUI unsubscribe itself from the thread (to protect against transmission after closing - Signal the thread to stop transmitting by altering a parameter I added (
running
) - Create the thread as a daemon
- Modify the
while
loop in the thread to be based off the newrunning
parameter so it can be told when to stop - Tell
app
to not have redirect (app = wx.App(False)
)
Take all of that into account and you're left with the following code:
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
import time
import threading
class GUI(wx.Frame):
def __init__(self, parent, id, title):
screenWidth = 500
screenHeight = 400
screenSize = (screenWidth,screenHeight)
wx.Frame.__init__(self, None, id, title, size=screenSize)
self.locationFont = locationFont = wx.Font(12, wx.MODERN, wx.NORMAL, wx.BOLD)
mainSizer = wx.BoxSizer(wx.VERTICAL)
myPanelA = wx.Panel(self, style=wx.SIMPLE_BORDER)
myPanelA.SetBackgroundColour('#C0FAE0')
self.myTextA = wx.StaticText(myPanelA, -1, "Testing")
mainSizer.Add(myPanelA, 1, wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Bind(wx.EVT_CLOSE, self.closeWindow)
pub.subscribe(self.updatePanelA, 'Update-panelA')
self.thd = threadA()
def updatePanelA(self, message):
self.myTextA.SetLabel(message)
def closeWindow(self, event):
# --> Code for killing the thread :)
pub.unsubscribe(self.updatePanelA, 'Update-panelA')
self.thd.running = False
self.Destroy()
class threadA(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.daemon = True
self.running = True
self.start()
def run(self):
while self.running:
time.sleep(2)
print 'Sending update'
wx.CallAfter(pub.sendMessage, 'Update-panelA', message='Yes, It works')
if __name__=='__main__':
app = wx.App(False)
frame = GUI(parent=None, id=-1, title="Problem Demo-PSS")
frame.Show()
app.MainLoop()
Hope this helps