问题出在加密时使用了字符的ASCII码进行加密,而解密时没有将加密后的字符重新转换成ASCII码,导致解密后的文件内容出现了乱码。解决方法是在解密时添加一个将字符转换成ASCII码的步骤。

修改后的代码如下:

def encrypt_decrypt_file(input_file_path, output_file_path, key): try: with open(input_file_path, 'rb') as input_file, open(output_file_path, 'wb') as output_file: text = input_file.read() result = "" n = len(key) for i in range(len(text)): c = chr(text[i]) if c.isalpha(): shift = ord(key[i % n]) - ord('a') if c.islower(): result += chr((ord(c) - ord('a') + shift) % 26 + ord('a')) else: result += chr((ord(c) - ord('A') + shift) % 26 + ord('A')) else: result += c output_file.write(result.encode('utf-8')) return True except Exception as e: messagebox.showerror("Error", str(e)) return False

def decrypt_file(input_file_path, output_file_path, key): try: with open(input_file_path, 'rb') as input_file, open(output_file_path, 'wb') as output_file: text = input_file.read() result = "" n = len(key) for i in range(len(text)): c = chr(text[i]) if c.isalpha(): shift = ord(key[i % n]) - ord('a') if c.islower(): result += chr((ord(c) - ord('a') - shift) % 26 + ord('a')) else: result += chr((ord(c) - ord('A') - shift) % 26 + ord('A')) else: result += c output_file.write(result.encode('utf-8')) return True except Exception as e: messagebox.showerror("Error", str(e)) return False

#此函数可以检查输入框是否填写完整,然后调用encrypt_decrypt_file或decrypt_file函数进行加密/解密操作 def on_encrypt_decrypt(mode): input_file_path = e_input.get() output_file_path = e_output.get() key = e_key.get() if not input_file_path or not output_file_path or not key: messagebox.showwarning("Warning", "请填写完整的输入、输出路径和密钥!") return if mode == 'encrypt' and encrypt_decrypt_file(input_file_path, output_file_path, key): messagebox.showinfo("Success", "文件加密成功!") elif mode == 'decrypt' and decrypt_file(input_file_path, output_file_path, key): messagebox.showinfo("Success", "文件解密成功!")

加密按钮

btn_encrypt = tk.Button(new_window, text="加密", command=lambda: on_encrypt_decrypt('encrypt')) btn_encrypt.pack()

解密按钮

btn_decrypt = tk.Button(new_window, text="解密", command=lambda: on_encrypt_decrypt('decrypt')) btn_decrypt.pack(

def create_new_window1 def encrypt_decrypt_fileinput_file_path output_file_path key try with openinput_file_path rb as input_file openoutput_file_path wb as output_file