【问题标题】:Python 3: urllib.request.urlopen and ProgressbarPython 3:urllib.request.urlopen 和 Progressbar
【发布时间】:2013-10-19 12:52:10
【问题描述】:

我是 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%。

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

【问题讨论】:

    标签: python python-3.x tkinter urllib2 urllib


    【解决方案1】:

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

    【讨论】:

    • 同样的事情也发生在我身上,但在 Java 中。不挂起 UI 的最好方法是创建一个单独的线程来完成这项工作,然后通过在屏幕上设置正确的数据定期向 UI 发送消息。确保在 UI 上公开您要修改的变量,以便从工作线程轻松访问!
    • 谢谢,解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2011-07-08
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多