[英]Tkinter - multithreading or multiprocessing in for loop
我想優化我的程序。 簡而言之,它用於解壓縮巨大的 tar.gz 存檔(5 gb+)或根據輸入從中提取一些文件(大約 20k)。
我現在面臨的主要問題是窗口沒有響應,但我真的需要它才能正常工作。 我已閱讀有關多處理和多線程的信息,但不確定如何將其應用於我的代碼。
請你幫我解決一下好嗎?
這是我的兩個解壓縮函數:
def unzip_tar_gz(self, ARES_tar_gz):
row = 22 #used for GUI
self.debug_output("Unzip", row, "Start: ")
tarfile_ARES = tarfile.open(ARES_tar_gz)
#counters for progress bar
self.counter = 0
self.maxcount = 1200000
#extract
for member in tarfile_ARES.getmembers():
self.update_idletasks()
member.name = os.path.basename(member.name)
result = re.search("(.*).xml", member.name)
res = result.group(1)
r = res[:-1]
num = int(r)
tarfile_ARES.extract(member, self.get_folder(num))
self.counter+=1
#debug
if self.counter%100000 == 0:
row += 1
self.debug_output("extract 100k", row, "Success")
#after extract, closing
showinfo("Success", message="The execution was successfully completed.")
self.pb.stop()
self.destroy()
和
def unzip_changes(self, delta_file_arr, inputARES):
row = 22 #used for GUI
#debug
self.debug_output("Unzip changes", row, "Start: ")
tarfile_ARES = tarfile.open(inputARES)
time_not_found = date.today().strftime("%Y-%m-%d")
file_not_found = open(self.logs_path + time_not_found + '.log', 'w')
#counters for progress bar
self.counter = 0
self.maxcount = 22000
#extract
for name in delta_file_arr:
self.update_idletasks()
self.counter +=1
try:
member = tarfile_ARES.getmember(name)
member.name = os.path.basename(member.name)
result = re.search("(.*).xml", member.name)
res = result.group(1)
r = res[:-1]
num = int(r)
tarfile_ARES.extract(member, self.get_folder(num))
except:
result = re.search("./VYSTUP/DATA/(.*).xml", name)
res = result.group(1)
file_not_found.write(res + "\n")
continue
#after extract, closing
self.pb.stop()
showinfo("Success", message="The execution was successfully completed.")
file_not_found.close()
self.destroy()
您應該為要運行的每個函數使用一個線程,因為如果不這樣做,tkinter 窗口將凍結,直到函數完成。 所以使用:
import threading
這是一個帶有按鈕的示例:
Button = tk.Button(text='Thread',command=lambda: threading.Thread(target=my_function).start())
如果你使用類:
self.Button = tk.Button(self, text='Thread',command=lambda: threading.Thread(target=self.my_function).start())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.