The following code shows an example of download widget using wx.ProgressDialog. The download function takes two input arguments: url and dest. dest is a destination file that it creates or overwrites. Example of usage is provided at the end of the code in the buttom. You can custimize this as needed for your application. For instance, you might open FileDialog before calling this function to see where user wants to save the file and pass it as a dest argument. download function returns False if Cancel button is pressed while downloading.

   1 #!/usr/bin/env python
   2 
   3 import wx
   4 import urllib
   5 import os
   6 
   7 def download(url, dest):
   8     dlg = wx.ProgressDialog("Download Progress",
   9                        "Please wait...",
  10                            style = wx.PD_CAN_ABORT
  11                             | wx.PD_APP_MODAL
  12                             | wx.PD_ELAPSED_TIME
  13                             | wx.PD_ESTIMATED_TIME
  14                             )
  15     dlg.Update(0, "Please Wait...")
  16     fURL = urllib.urlopen(url)
  17     header = fURL.info()
  18     size = None
  19     max = 100
  20     outFile = open(dest, 'wb')
  21     keepGoing = True
  22     if "Content-Length" in header:
  23         size = int(header["Content-Length"])
  24         kBytes = size/1024
  25         downloadBytes = size/max
  26         count = 0
  27         while keepGoing:
  28             count += 1
  29             if count >= max:
  30                 count  = 99
  31             (keepGoing, skip) = dlg.Update(count, "Downloaded "+str(count*downloadBytes/1024)+
  32                                                   " of "+ str(kBytes)+"KB")
  33             b = fURL.read(downloadBytes)
  34             if b:
  35                 outFile.write(b)
  36             else:
  37                 break
  38     else:
  39             while keepGoing:
  40                 (keepGoing, skip) = dlg.UpdatePulse()
  41                 b = fURL.read(1024*8)
  42                 if b:
  43                     outFile.write(b)
  44                 else:
  45                     break
  46     outFile.close()
  47 
  48     dlg.Update(99, "Downloaded "+ str(os.path.getsize(dest)/1024)+"KB")
  49     dlg.Destroy()
  50     return keepGoing
  51 
  52 if __name__ == "__main__":
  53     app = wx.App()
  54     download('http://voxel.dl.sourceforge.net/sourceforge/wxpython/wxPython-docs-2.8.9.2.tar.bz2'
  55              , 'wxPython-docs-2.8.9.2.tar.bz2')

DownloadWidget (last edited 2010-01-17 20:54:25 by 79-65-133-135)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.