我有几个计算在没有任何用户输入的情况下运行,并且没有用户担心程序已经冻结,所以我试图显示一个进度条弹出窗口,让他们知道发生了什么。
环顾四周让我相信我需要使用一个单独的线程才能做到这一点,我想出了这个例子。
import threading, wx, time
MAX_INT = 10
TEST_TUPLE = [[11, 22],[33,44]]
class mainFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title)
bt = wx.Button(self, wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.onBt, bt)
def onBt(self,event):
self.dlg = wx.ProgressDialog("title", "message", maximum=MAX_INT)
workThread = threading.Thread(target=self.doWork, args=(TEST_TUPLE,) )
workThread.start()
self.dlg.ShowModal()
def doWork(self, testArg):
# time consuming stuff that affects main GUI
print testArg
for i in range(1, MAX_INT+1):
self.SetPosition((i*4*MAX_INT, i*2*MAX_INT))
time.sleep(1)
print str(i)+" of "+str(MAX_INT)
wx.CallAfter(self.dlg.Update, i, "%i of %i"%(i, MAX_INT))
self.dlg.Destroy()
app = wx.App(False)
fr = mainFrame(None, -1, "Title")
fr.Show()
app.MainLoop()
它似乎按预期工作,但是我在这里跳过一些管家吗?
编辑:我用miniframe替换了对话框,因此主窗口不会冻结,禁用按钮,因此不会产生多个帧,并添加了粗略的取消方法。
import threading, wx, time
MAX_INT = 10
TEST_TUPLE = [[11, 22],[33,44]]
class GaugeFrame(wx.MiniFrame):
def __init__(self, parent, title, maximum):
wx.MiniFrame.__init__(self, parent, title=title, size=(200, 60) )
self.bar = wx.Gauge(self, range=maximum)
self.buCancel = wx.Button(self, label="Cancel")
self.SetBackgroundColour("LTGRAY")
siMainV = wx.BoxSizer(wx.VERTICAL)
siMainV.Add(self.bar)
siMainV.Add(self.buCancel, flag=wx.CENTER)
self.SetSizer(siMainV)
self.Fit()
self.Bind(wx.EVT_BUTTON, self.onCancel, self.buCancel)
def updateGauge(self, value, message=""):
self.bar.SetValue(value)
if message!="":
self.SetTitle(message)
def onCancel(self, e):
self.SetTitle("Cancelling...")
class MainFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title)
self.bt = wx.Button(self, wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.onBt, self.bt)
def onBt(self, event):
self.gFr = GaugeFrame(self, title="0 of "+str(MAX_INT), maximum=MAX_INT)
self.gFr.Show()
self.gFr.Center()
self.bt.Disable()
workThread = threading.Thread(target=self.doWork, args=(TEST_TUPLE,) )
workThread.start()
def doWork(self, testArg):
# time consuming stuff that affects main GUI
print testArg
for i in range(1, MAX_INT+1):
time.sleep(1)
if self.gFr.GetTitle()=="Cancelling...":
break
print str(i)+" of "+str(MAX_INT)
wx.CallAfter(self.gFr.updateGauge, i, "%i of %i"%(i, MAX_INT))
wx.CallAfter(self.gFr.Destroy)
wx.CallAfter(self.bt.Enable)
app = wx.App(False)
fr = MainFrame(None, -1, "Title")
fr.Show()
app.MainLoop()
答案 0 :(得分:1)
看起来很不错,只是一些观察。
SetPosition
和Destroy
。您可以使用wx.CallAfter
在主线程上调用这些内容,就像使用Update
一样。