Python 3 : urllib. request.urlopen 和 Progressbar

标签 python python-3.x tkinter urllib2 urllib

我是 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%,我将运行代码并进行调查。

关于Python 3 : urllib. request.urlopen 和 Progressbar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19466220/

相关文章:

python - 如何使用 dbf 模块更新记录

python - Django 不匹配 url 中的 unicode

python - 按键释放时的 Tkinter <Return> 事件

python - Tkinter GUI 卡住

python - matlab数据文件到pandas DataFrame

python - 给定 3 个变量具有相同的值,将一个值与一行匹配?

python - 如何找到有意义的词来表示从 word2vec 向量派生的每个 k-means 聚类?

python-3.x - 以编程方式将新菜单项添加到菜单项 PyGObject?

Python 秒表示例 - 同时启动所有类实例?

python - 使用 python 的 lxml 剥离内联标签