有非常相似的问题,但我要么不理解,要么没有完全回答。我见过的这两个是这个和这个。我有一个 wxpython GUI 正在运行。按下按钮,我运行四个不同的线程(运行时间很长的任务)。我已经能够实现这个没有问题——线程运行并且我仍然可以使用 GUI。
每个线程(TestThread0
,TestThread1
等)将一个变量写入文件(但永远不会完成它的循环——无限循环)。每隔一段时间(比如每 20 秒),我想WriteThis
在我的主 GUI 应用程序 (wx.FRAME) 中运行一个函数 (),以读取此文件及其值/变量。我的问题是如何在线程仍在运行时在 GUI 部分运行此功能?当我尝试运行时,我的错误开始发挥作用TMainForm.WriteThis()
。
以下是我的(非常简短的)代码:
class TMainForm(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER
wx.Frame.__init__(self, *args, **kwds)
self.Splitter = wx.SplitterWindow(self, -1)#, style=wx.SP_NOSASH)
self.Panel1 = wx.Panel(self.Splitter, -1)
self.Panel3 = wx.Panel(self.Splitter, -1)
self.Splitter.SplitVertically(self.Panel1,self.Panel3,400)
... and so on to set up GUI
# Press button in GUI to run threads
def OnAnalyzePress(self,event):
TestThread0()
time.sleep(2)
TestThread1()
time.sleep(2)
TestThread2()
time.sleep(2)
TestThread_output
# This is the function I want to run from TestThread_output class below
def WriteThis(self):
print 'Running'
# I will read file and update GUI here (Threads keep running though)
# Example thread (all the others are the same)
class TestThread0(Thread):
def __init__(self):
Thread.__init__(self)
self.start() # start the thread
def run(self):
# This is my "infinite loop" function that writes variable/values to a file
MyLongRunningFunction.SomeFunction()
# This is the thread I want to run that executes some function in wx.FRAME every 20 seconds
class TestThread_output(Thread):
def __init__(self):
Thread.__init__(self)
self.start() # start the thread
def run(self):
for i in range(1000):
TMainForm.WriteThis() # !!! This is where my error is !!! I want to run function called "WriteThis"
time.sleep(20)
class TApplication(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
MainForm = TMainForm(None, -1,"")
self.SetTopWindow(MainForm)
MainForm.Show()
return 1
if __name__ == "__main__":
Application = TApplication(0)
Application.MainLoop()
谢谢你的帮助!!