2

我想根据它们的名称(,,...)从远程服务器下载http://mysite.com/id?id=abc1图像http://mysite.com/id?id=abc2

下载部分有效,但由于可能有很多文件要下载(有时超过 200 个),我想添加一个标签“请稍候”(Tkinter)。问题是我的标签只有在下载完成时才会出现,这当然不是很有用。

我怎样才能让它更早出现?

from Tkinter import *
import urllib2
import time

window = Tk()
window.title('My Downloader')
photo=PhotoImage(file="logo.gif")
labl = Label(window, image=photo)
labl.pack()
mainid = Label(window, text = 'Main id:')
mid = Entry(window)
complete = Label(window, text = 'download complete !')

def dl():
    right = Label (window, text ='downloading...Please wait')
    right.pack()
    time.sleep(2)
    i='10'

    while int(i) <= 100000 :
        if len(str(i))==1:
            i="0000"+str(i)
        elif len(str(i))==2:
            i="000"+str(i)
        elif len(str(i))==3:
            i="00"+str(i)
        elif len(str(i))==4:
            i="0"+str(i)

        url = 'http://mysite.com/id?recordID='+ str(mid.get())+str(i)

        try:
            dltest = urllib2.urlopen(url)            
            with open(str(mid.get())+str(i)+'.tiff', 'wb') as f:
                while True:
                    content = dltest.read()
                    if not content: break
                    f.write(content)                
        except urllib2.URLError:            
            if int(i)==10:
                wrong = Label (window, text ='wrong id ')
                wrong.pack()
                break
            else:                
                complete.pack()
                break                                       
        i=int(i)+10
dlbutton = Button(window, text =' Download!', command=dl)
mainid.pack()
mid.pack()
dlbutton.pack() 
window.mainloop()
4

1 回答 1

2

设置标签后只需调用 window.update() 即可。

right = Label (window, text ='downloading...Please wait')
right.pack()
window.update()

但更好的做法是对 URL 下载进行线程化。这可能是一项相当复杂的任务,但允许您在下载文件时释放 GUI。查看此页面,了解如何线程化您的程序。

于 2012-12-08T12:53:28.347 回答