2014-07-20 55 views
0

嗨,所以我有我的代碼(可能不是urllib2本身)的問題,但它不會創建進度欄和崩潰。但等待代碼完成後下載我的文件。反正我有可以防止懸掛和可能打破的下載成小塊,因爲我有蟒蛇一點經驗...我的代碼如下:運行urllib2進度條調用崩潰程序

def iPod1(): 
pb = ttk.Progressbar(orient ="horizontal",length = 200, mode ="indeterminate") 
pb.pack(side="top") 
pb.start() 
download = "http://downloads.sourceforge.net/project/whited00r/7.1/Whited00r71-iPodTouch1G.zip?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fwhited00r%2Ffiles%2F7.1%2F&ts=1405674672&use_mirror=softlayer-ams" 
request = urllib2.urlopen(download) 
pb.start() 
output = open("Whited00r71-iPodTouch1G.zip", "wb") 
output.write(request.read()) 
output.close() 
pb.stop 
tkMessageBox.showinfo(title="Done", message="Download complete. Please follow the installation instructions provided in the .html file.") 
+0

顯示完整的錯誤訊息。有問題的行數 - 在代碼中標記此行。 – furas

+0

你在console/terminal/cmd.exe中運行過它嗎?您在關閉它時是否在console/terminal/cmd.exe中收到任何消息? – furas

+0

它真的停下來好嗎?您的代碼在整個下載期間肯定會阻止/凍結GUI,但應該在之後繼續。 – BlackJack

回答

0

的懸掛/可避免GUI凍結將下載移動到它自己的線程中。由於GUI不能從Tk主循環運行的另一個線程中更改,我們必須定期檢查下載線程是否已完成。這通常通過在窗口小部件對象上重複使用after()方法來安排延遲函數調用來完成。

在將文件寫入本地文件之前,不能將整個文件讀入內存可以使用shutil.copyfileobj()完成。

import shutil 
import tkMessageBox 
import ttk 
import urllib2 
from threading import Thread 

IPOD_1_URL = (
    'http://downloads.sourceforge.net/project/whited00r/7.1/' 
    'Whited00r71-iPodTouch1G.zip' 
    '?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fwhited00r%2Ffiles%2F7.1%2F' 
    '&ts=1405674672' 
    '&use_mirror=softlayer-ams' 
) 


def download(url, filename): 
    response = urllib2.urlopen(url) 
    with open(filename, 'wb') as output_file: 
     shutil.copyfileobj(response, output_file) 


def check_download(thread, progress_bar): 
    if thread.is_alive(): 
     progress_bar.after(500, check_download, thread, progress_bar) 
    else: 
     progress_bar.stop() 
     tkMessageBox.showinfo(
      title='Done', 
      message='Download complete. Please follow the installation' 
       ' instructions provided in the .html file.' 
     ) 


def start_download_for_ipod1(): 
    progress_bar = ttk.Progressbar(
     orient='horizontal', length=200, mode='indeterminate' 
    ) 
    progress_bar.pack(side='top') 
    progress_bar.start() 
    thread = Thread(
     target=download, args=(IPOD_1_URL, 'Whited00r71-iPodTouch1G.zip') 
    ) 
    thread.daemon = True 
    thread.start() 
    check_download(thread, progress_bar) 
+0

@ itechy21那不是被按鈕調用的函數。 'start_download_for_ipod1()'函數是開始下載的函數。 – BlackJack

+0

感謝您的理解。 – iTechy