我是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%。
有没有更好的方法可以做到这一点,而无需挂断接口?
不要一口气读取数据;这会阻塞用户界面。取而代之的是,通过使字节的量读出的数据的一个小的量(例如字节1024分之8192) open.read()
,例如open.read(1024)
。读取数据之后,使用刷新app.update()
应用程序的UI ,假设app是Tk实例(在代码中的某个位置,您应该向分配了一些变量Tk()
)。将其放入while循环中,并在read()
函数返回空字节字符串(b""
)(表示下载完成)时停止while外观。不知道为什么进度条从0跳到100%,我将运行代码并进行调查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句