I'm making an Python program which downloads files. I use Tkinter as GUI, but it freezes while it's downloading larger files which stops buffer from showing. I tried to use threading, as it's suggested in similar questions on SO but nothing changed. Here's code:
labelText1 = StringVar()
labelText1.set("Double-click file to download...")
label11 = Label(app, textvariable=labelText1, height=2, bg="#DF1A2B", fg="white")
label11.place(x=50, y=50)
def download_file(url):
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open("./downloads/" + file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s" % (file_name)
os.system('cls')
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
labelText1.set(status,)
tuple = (file_name, status)
f.close()
onEnd()
def onEnd():
labelText1.set("Status: done!")
def double_clicked(clicked):
tuple = mlb.get(clicked)[0]
url = str(tuple[2])
if tuple[1] != "Folder":
t = threading.Thread(target=download_file(url))
t.start()
else:
print "FOLDER HANDLING GOES HERE"
Is there any other way which will allow me to change label text while download process is still running?
Just because it's in a separate thread the GUI can still "hang" if it has a long section of code in it (eg your while loop). Add a GUI refresh during the while loop so that it gets a chance to redraw, eg using update()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.