我是Python的新手,在获取某些HTML文件/网址的内容时遇到问题,并使用进度条显示状态:
这是我使用的相关代码:
进度:
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%。
有没有更好的方法可以做到这一点,而不会挂断界面?
答案 0 :(得分:1)
不要一次性读取数据;这会阻止用户界面。相反,通过将字节量传递给open.read()
,例如,读取少量数据(例如8192/1024字节)。 open.read(1024)
。读取数据后,使用app.update()
刷新UI,假设app是Tk实例(代码中的某个位置,您应该将一些变量分配给Tk()
)。将此放在while循环中并在read()
函数返回空字节字符串(b""
)时停止while看,表示下载完成。不确定为什么进度条从0跳到100%,我将运行代码并进行调查。