我一直在開發一個 tkinter 應用程式,用于從 Internet 下載檔案并在進度條 (Progressbar) 上顯示它的進度。
由于下載程序與 GUI 不同,(并且由于 tkinter 在無限回圈中運行 GUI 主執行緒),我想為下載程序創建一個不同的執行緒,它會更新進度條背景
然后我會繼續等待后臺行程結束,并呼叫 root.destroy() 方法來結束應用程式,但應用程式沒有關閉,手動關閉應用程式 - 它會回傳以下錯誤
_tkinter.TclError:無法呼叫“銷毀”命令:應用程式已被銷毀
這是代碼
class download:
#Initializing the root
def __init__(self):
self.root = Tk()
#creating the progress bar and packing it to the root
def create_progress_bar(self):
self.progress_bar = Progressbar(self.root, orient = HORIZONTAL, length = 200, mode = 'determinate')
self.progress_bar.pack(pady=10)
#function to start the mainloop
def start_application(self):
self.root.mainloop()
#updating the progress bar from the background thread
def update_progress(self, count, blocksize, totalsize):
update = int(count * blocksize * 100 / totalsize)
self.progress_bar['value'] = update
self.root.update_idletasks()
#downloading the file from the background thread
def download_file(self, download_url):
#using the reporthook to get information about download progress
urllib.request.urlretrieve(download_url, 'a.jpg', reporthook=self.update_progress)
#closing the root function
def close(self):
self.root.destroy()
#handling the download
def handle_download(self, download_url):
#creating a different thread
self.process = Thread(target=self.download_file, args=(download_url,))
#creating the progress bar
self.create_progress_bar()
#starting the background thread
self.process.start()
#starting the GUI
self.start_application()
#waiting for the background thread to end
self.process.join()
#closing the application
self.close()
ob = download()
ob.handle_download('link')
值得一提的是,我確實嘗試在同一執行緒上進行處理,但應用程式無法回應更新。對此事的任何見解都將非常受歡迎。
uj5u.com熱心網友回復:
由于您的程式self.root.destroy()僅在self.root.mainloop()回傳后才執行,因此除非您手動關閉應用程式,否則它不會達到破壞點,然后呼叫.destroy().
您可以不時檢查下載執行緒是否正在運行,如果沒有,則銷毀視窗。
def watch(self):
if self.process.is_alive(): self.root.after(500, self.watch)
else: self.close()
#handling the download
def handle_download(self, download_url):
…
#starting the background thread
self.process.start()
self.watch()
…
#closing the application
#self.close() is too late here
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345024.html
