wxPython线程wxGauge

时间:2014-02-02 00:27:47

标签: multithreading wxpython

我正在尝试使用wxPython学习线程,所以我试图让这个简单的例子工作,但似乎进度条更新发生在“漫长过程”完成之后。谁能告诉我为什么这不起作用?

#!/usr/bin/env python
import time
import wx
from wx.lib.pubsub import Publisher as pub


class Window(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="wxGauge")
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.gauge = wx.Gauge(self, range=10)
        self.btn = wx.Button(self, label="Start process")
        self.sizer.Add(self.gauge)
        self.sizer.Add(self.btn)
        self.SetSizerAndFit(self.sizer)
        pub.subscribe(self.update, "update")
        self.btn.Bind(wx.EVT_BUTTON, self.OnClick)
        self.Show()

    def update(self, msg):
        self.gauge.SetValue(msg.data)

    def OnClick(self, evt):
        for i in range(10):
            wx.CallAfter(pub.sendMessage, "update", i + 1)
            time.sleep(1)

if __name__ == '__main__':
    app = wx.App()
    Window()
    app.MainLoop()

1 个答案:

答案 0 :(得分:0)

这是因为使用了“CallAfter”。如果以这种方式调用“sendMessage”,它实际上是在事件处理程序完成后调用的。

你可以这样试试:

for i in range(10):
    pub.sendMessage("update", i+1)
    time.sleep(1)

修改

将此“sendMessage”放在事件处理程序之外。

    import time
    import wx
    from wx.lib.pubsub import Publisher as pub

    class Window(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None, title="wxGauge")
            self.sizer = wx.BoxSizer(wx.VERTICAL)
            self.gauge = wx.Gauge(self, range=10)
            self.btn = wx.Button(self, label="Start process")
            self.sizer.Add(self.gauge)
            self.sizer.Add(self.btn)
            self.SetSizerAndFit(self.sizer)
            pub.subscribe(self.update, "update")
            self.btn.Bind(wx.EVT_BUTTON, self.OnClick)

            self.Bind(wx.EVT_TIMER, self.TimerHandler)
            self.timer = wx.Timer(self)
            self.gaugeIndex = 0
            self.Show()

        def TimerHandler(self, event):
            self.gaugeIndex += 1
            pub.sendMessage("update", self.gaugeIndex)
            if self.gaugeIndex == 10:
                self.timer.Stop()

        def update(self, msg):
            self.gauge.SetValue(msg.data)

        def OnClick(self, evt):
            self.timer.Start(1000)


    if __name__ == '__main__':
        app = wx.App(redirect=False)
        Window()
        app.MainLoop()