Skip to main content
 首页 » 编程设计

Python 3 : urllib. request.urlopen 和 Progressbar

2025年05月04日10thcjp

我是 Python 的新手,在获取某些 HTML 文件/URL 的内容并使用进度条显示状态时遇到问题:

这是我使用的相关代码:

进度条:

def createProgressbar(self): 
        self.progressbarVar = StringVar() 
        self.progressbar = ttk.Progressbar( self.masterWindow, variable=self.progressbarVar, length=400, maximum=100, mode='determinate' ) 
        self.progressbar.place(x=100, y=760) 
 
        self.progressbarStatus = Label( self.masterWindow, text='Please wait ...', bg='#fafafa', fg='#333', bd=0 ) 
        self.progressbarStatus.place(x=100, y=730) 

阅读 HTML:

def readHTML(self): 
        # Set new progressbar max, eg. 20 for 20 files to read 
        self.progressbar.config(maximum=self.LinkListItemCount) 
 
        # Progressbar Counter 
        i=1 
 
        # example for self.LinkListByCatDict 
        # self.LinkListByCatDict = {'cat1': ['/test/asd.html', '/test/asd2.html'], 'cat2': ['/test/asd.html', '/test/asd2.html']} 
 
        for item in self.LinkListByCatDict.items(): 
            actCategory = item[0] 
 
            for linkItem in item[1]: 
                url = 'http://www.example.com'+linkItem 
 
                try: 
                    req = urllib.request.Request( url ) 
                    open = urllib.request.urlopen( req ) 
                    requestContent = open.read() 
 
 
                    if self.debug == True: 
                        print('OK: '+url) 
                except: 
                    if self.debug == True: 
                        print('Error: '+url) 
 
 
                # Progressbar update 
                self.progressbarVar.set(i) 
 
                if self.debug == True: 
                    print('Progressbar act: '+str(i)) 
 
                i += 1 

一般情况下工作正常,但在处理循环时整个界面只显示一个沙滩球 (Mac OS)。循环结束时进度条从0直接跳到100%。

有没有更好的方法来做到这一点,而不挂断界面?

请您参考如下方法:

不要一口气读取数据;那会阻止用户界面。相反,通过将字节数传递给 open.read() 来读取少量数据(例如 8192/1024 字节),例如打开.读取(1024)。读取数据后,使用 app.update() 刷新 UI,假设 app 是 Tk 实例(在您的代码中的某处,您应该已将一些变量分配给 Tk() ).将其置于 while 循环中,并在 read() 函数返回空字节字符串 (b"") 时停止 while 查找,表明下载已完成。不确定为什么进度条会从 0 跳到 100%,我将运行代码并进行调查。