我有一些代码要求用户导入文件,然后使用翻译器对其进行加密。当我尝试这个时,程序会挂起大量文件或任何文件。我尝试使用线程和进度条来解决这个问题,但我已经走到了尽头 - 我不知道如何更新进度条,这将与需要花费的时间相对应加密文件。这就是我到目前为止所做的:
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import *
import threading
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVZMNXPBDCRJTQEGHK'
letters += letters.lower()
encryption_code += encryption_code.lower()
enc = dict(zip(letters,encryption_code))
window = tkinter.Tk()
style = ttk.Style(window)
style.configure("BW.TLabel")
import_frame = tkinter.Frame(window)
def import_txt():
global import_list
file_name = askopenfilename(filetypes=[("Text files","*.txt")])
import_list = []
with open(file_name, 'r') as f:
import_list = f.readlines()
progressbar.pack()
but1.pack()
encrypttxt.pack()
f.close()
def encrypt_txt():
global letters
global encryption_code
global import_list
global translated
progressbar.start()
pre = "".join(import_list)
translated = "".join([i.translate(str.maketrans(letters, encryption_code)) for i in import_list])
display_txt.insert('insert', translated)
precrypt.insert('insert', pre)
display_txt.pack(side=RIGHT)
precrypt.pack(side=LEFT)
def end():
if t.isAlive() == False:
progressbar.stop()
t.join()
toplevel = tkinter.Toplevel(window)
progressbar = ttk.Progressbar(toplevel, orient = HORIZONTAL, mode = "determinate")
t = threading.Thread(target=encrypt_txt)
but1 = ttk.Button(window, text= "Stop", command=end)
display_txt = tkinter.scrolledtext.ScrolledText(import_frame)
encrypttxt = ttk.Button(import_frame, text="Encrypt", command=encrypt_txt)
precrypt = tkinter.scrolledtext.ScrolledText(import_frame)
start = ttk.Button(window, text="Start", command=import_txt)
start.pack()
import_frame.pack()
window.mainloop()