问题描述
限时送ChatGPT账号..我想要一个向用户显示下载进度的进度条.更新GUI并同时下载时,进度条冻结,我明白为什么,但我不知道如何解决.我使用这篇文章尝试了多线程:Tkinter:如何使用线程来防止来自冻结" 和使用 Python 基础知识的主事件循环多线程和队列作为帮助我满足我需求的指南.问题是,我尝试以哪种方式实现目标,但在更改它以执行我需要它做的事情时似乎总是犯错误.
I want a progress bar that shows the user the download progress. When updating the GUI and downloading at the same time the progress bar freezes, and I understand why but I don't know how to solve it. I tried multithreading using this post: Tkinter: How to use threads to preventing main event loop from "freezing" and using The Basics of Python Multithreading and Queues as a guid to help me fit it to my needs. The problem is that which way I try to achieve my goal, I always seem to make a mistake when changing it to do what I need it to do.
我的代码的最基本版本(没有多线程):
The most basic version of my code (without multithreading):
from Tkinter import *
import ttk
from urllib import URLopener # Downloading files
# Make frame to tell user what file is getting downloaded
self.Progressmsg = Label(self, text="TempValue")
self.Progressmsg.pack(pady=(10,0))
# Make progress bar to show user download progress
self.Progressbar = ttk.Progressbar(self, mode="determinate", orient='horizontal', lengt=280, maximum=len(self.AllClasses))
self.Progressbar.pack(padx=10, pady=10)
self.Progressbar["value"] = 0
def DownloadFile(Class):
# Update progress message
self.Progressmsg["text"] = "Downloading {0}.ics...".format(Class)
# Download each file from saxion website
CalFile = URLopener()
CalFile.retrieve("http://[school website]/ical/group/{0}.ics".format(Class), "Data/{0}.ics".format(Class))
# Update progress bar
self.Progressbar["value"] += 1
for Study in self.Parameters["Classes"]:
for Class in Study:
DownloadFile(Class)
注意:在这段代码中,AllClasses
是一个不同类的列表,日历文件必须从这些类中下载.
代码本身是我没有包含的相当大的类的一部分.这就是为什么我使用 self.[variablename]
Notes: In this code AllClasses
is a list of different classes from which a calendar file has to be downloaded.
The code itself is part of a fairly large class which I didn't include. This is why I am using self.[variablename]
当此代码运行时,进度条不会加载或更新,所有文件都会正确下载,下载时进度条会立即更新所有内容.我的问题是:我该如何解决这个问题?
When this code runs the progressbar doesn't load or update, all the files download properly and when they are downloaded the progress bar updates everything at once. My question is: how do I solve this problem in my case?
推荐答案
试试这个:
# Update progress bar
self.Progressbar["value"] += 1
self.Progressbar.update_idletasks()
如果它不起作用,则使用 self.Progressbar.update()
代替.
If it does not work then use self.Progressbar.update()
instead.
除非您调用 update_idletasks()
或 update()
,否则如果有其他事情要做(例如下载下一个文件),GUI 将不会反映您的更改.
The GUI won't reflect your changes if there is something else to do (like downloading the next file) unless you call update_idletasks()
or update()
.
这篇关于ttk进度条冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论