简体   繁体   中英

wxpython progress bar for saving file

I've been trying to figure out how can I display a progress dialog during saving file dialog.

Right now it displayed, but the bar doesn't move until the file dialog gets destroyed.

dlg = wx.FileDialog(
        self, message="Save file as ...",
        defaultFile="", wildcard="Excel Files (*.xlsx)|*.xlsx", style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT
        )
    if dlg.ShowModal() == wx.ID_OK:
        path = dlg.GetPath()

        try:
            self.progress = wx.GenericProgressDialog("Saving file ...", "", 100, self, wx.PD_AUTO_HIDE|wx.PD_APP_MODAL|wx.PD_SMOOTH)
            self.progress.Pulse()
            #do long running task and save file
            self.timer.Stop()
            self.progress.Destroy()
            wx.MessageBox('Saved at ' + path)
        except:
            print "Error saving:", sys.exc_info()[0]
            raise
    dlg.Destroy()

def OnTimer(self, event):
        if self.progress != None and self.progress_cnt < 100:
            self.progress_cnt += 5
            self.progress.Update(self.progress_cnt)

Use wx.Yield() in every iteration or (n) many iterations of the "long running task".

import wx
import sys
import time
class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Statusbar',size=(300,200))
        panel = wx.Panel(self)
        self.Show()
        dlg = wx.FileDialog(
            self, message="Save file as ...",
            defaultFile="", wildcard="Excel Files (*.xlsx)|*.xlsx", style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            try:
                self.progress = wx.GenericProgressDialog("Saving file ...", "", 100, self, wx.PD_AUTO_HIDE|wx.PD_APP_MODAL|wx.PD_SMOOTH)
                x=0
                while x < 20:       #do long running task and save file
                    x+=1            #do long running task and save file
                    time.sleep(0.5) #do long running task and save file
                    self.progress.Pulse("Hamster running like fury")
                    wx.Yield()      #use Yield to allow update of progress bar
                self.progress.Destroy()
                wx.MessageBox('Saved at ' + path)
            except:
                print "Error saving:", sys.exc_info()[0]
                raise
        dlg.Destroy()

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

My long running process is while x < 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM