[英]Tkinter - multithreading or multiprocessing in for loop
I would like to optimize my program.我想优化我的程序。 In short, it is used to unzip huge tar.gz archive (5 gb+) or extract some file from it (approx. 20k) based on input.
简而言之,它用于解压缩巨大的 tar.gz 存档(5 gb+)或根据输入从中提取一些文件(大约 20k)。
The main problem I am facing right now is that window is not responding, but I really need it to work properly.我现在面临的主要问题是窗口没有响应,但我真的需要它才能正常工作。 I have read about multiprocessing and multithreading, but not sure how to apply it on my code.
我已阅读有关多处理和多线程的信息,但不确定如何将其应用于我的代码。
Could you, please, help me with it?请你帮我解决一下好吗?
Here are 2 my functions for unziping:这是我的两个解压缩函数:
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()
and和
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()
You should use a thread for each function you want run because if you don't, the tkinter window will freeze until the function finish for example.您应该为要运行的每个函数使用一个线程,因为如果不这样做,tkinter 窗口将冻结,直到函数完成。 So use:
所以使用:
import threading
Here an example with a button:这是一个带有按钮的示例:
Button = tk.Button(text='Thread',command=lambda: threading.Thread(target=my_function).start())
if you use class:如果你使用类:
self.Button = tk.Button(self, text='Thread',command=lambda: threading.Thread(target=self.my_function).start())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.