我想要一个开始执行文件的按钮,以及另一个停止执行的按钮。以下代码不起作用,文件继续执行。 (在这种情况下,文件只是一个循环,不断打印出“hello world”。)我如何实现我的目标?
import wx, sys
from threading import Thread
import time
class mywxframe(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None)
pnl = wx.Panel(self)
szr = wx.BoxSizer(wx.VERTICAL)
pnl.SetSizer(szr)
szr2 = self.sizer2(pnl)
szr.Add(szr2, 1, wx.ALL|wx.EXPAND, 10)
log = wx.TextCtrl(pnl, -1, style= wx.TE_MULTILINE, size = (300, -1))
szr.Add(log, 0, wx.ALL, 10)
btn3 = wx.Button(pnl, -1, "Stop")
btn3.Bind(wx.EVT_BUTTON, self.OnStop)
szr.Add(btn3, 0, wx.ALL, 10)
self.CreateStatusBar()
redir = RedirectText(log)
sys.stdout=redir
szr.Fit(self)
self.Show()
def sizer2(self, panel):
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.tc2 = wx.TextCtrl(panel, -1, 'Set Range', size = (100, -1))
btn2 = wx.Button(panel, -1, "OK",)
self.Bind(wx.EVT_BUTTON, self.OnStart, btn2)
sizer.Add(self.tc2, 0, wx.ALL, 10)
sizer.Add(btn2, 0, wx.ALL, 10)
return sizer
def OnStart(self, event):
our_thread = Thread(target = self.WorkerThread)
our_thread.start()
def OnStop(self, event):
self.dead = True
def WorkerThread(self):
self.dead = False
while (not self.dead):
execfile("P:\Computing and networking\Python\Learning programs\hello_world.py")
if self.dead:
break
print "aborting"
class RedirectText(object):
def __init__(self, aWxTextCtrl):
self.out=aWxTextCtrl
def write(self, string):
wx.CallAfter(self.out.WriteText, string)
app = wx.App()
frm = mywxframe()
app.MainLoop()
答案 0 :(得分:0)
您的GUI变得反应迟钝。这意味着您的长时间运行过程会阻止GUI的主循环。要使其工作,您需要子类Thread。这是一个适合我的版本:
import wx, sys
from threading import Thread
import time
class TestThread(Thread):
def __init__(self):
Thread.__init__(self)
self.dead = False
self.start()
def run(self):
while not self.dead:
print "hi"
print "aborted"
class mywxframe(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None)
pnl = wx.Panel(self)
szr = wx.BoxSizer(wx.VERTICAL)
pnl.SetSizer(szr)
szr2 = self.sizer2(pnl)
szr.Add(szr2, 1, wx.ALL|wx.EXPAND, 10)
log = wx.TextCtrl(pnl, -1, style= wx.TE_MULTILINE, size = (300, -1))
szr.Add(log, 0, wx.ALL, 10)
btn3 = wx.Button(pnl, -1, "Stop")
btn3.Bind(wx.EVT_BUTTON, self.OnStop)
szr.Add(btn3, 0, wx.ALL, 10)
self.CreateStatusBar()
redir = RedirectText(log)
#sys.stdout=redir
szr.Fit(self)
self.Show()
def sizer2(self, panel):
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.tc2 = wx.TextCtrl(panel, -1, 'Set Range', size = (100, -1))
btn2 = wx.Button(panel, -1, "OK",)
self.Bind(wx.EVT_BUTTON, self.OnStart, btn2)
sizer.Add(self.tc2, 0, wx.ALL, 10)
sizer.Add(btn2, 0, wx.ALL, 10)
return sizer
def OnStart(self, event):
self.our_thread = TestThread()
def OnStop(self, event):
self.our_thread.dead = True
class RedirectText(object):
def __init__(self, aWxTextCtrl):
self.out=aWxTextCtrl
def write(self, string):
wx.CallAfter(self.out.WriteText, string)
app = wx.App()
frm = mywxframe()
app.MainLoop()
您可能需要查看以下资源,以获取有关wxPython和线程的其他信息: