from tkinter import * from crypto.Cipher import DES def encrypt(): key = bytes(key_entry.get(), 'utf-8') cipher = DES.new(key, DES.MODE_ECB) plaintext = bytes(plaintext_entry.get(), 'utf-8') ciphertext = cipher.encrypt(plaintext) ciphertext_entry.delete(0, END) ciphertext_entry.insert(0, ciphertext.hex()) def decrypt(): key = bytes(key_entry.get(), 'utf-8') cipher = DES.new(key, DES.MODE_ECB) ciphertext = bytes.fromhex(ciphertext_entry.get()) plaintext = cipher.decrypt(ciphertext) plaintext_entry.delete(0, END) plaintext_entry.insert(0, plaintext.decode('utf-8')) root = Tk() plaintext_label = Label(root, text="Plaintext:") plaintext_label.grid(row=0, column=0) plaintext_entry = Entry(root) plaintext_entry.grid(row=0, column=1) key_label = Label(root, text="Key:") key_label.grid(row=1, column=0) key_entry = Entry(root) key_entry.grid(row=1, column=1) encrypt_button = Button(root, text="Encrypt",command=encrypt) encrypt_button.grid(row=2, column=0) decrypt_button = Button(root, text="Decrypt",command=decrypt) decrypt_button.grid(row=2, column=1) ciphertext_label = Label(root, text="Ciphertext:") ciphertext_label.grid(row=3, column=0) ciphertext_entry = Entry(root) ciphertext_entry.grid(row=3, column=1) root.mainloop()
时间: 2024-02-28 18:56:12 浏览: 55
Python库 | assemblyline_ui-4.2.0.24-py3-none-any.whl
这段代码存在一个问题:在函数 `encrypt()` 中,程序尝试使用一个名为 `plaintext_entry` 的变量,但是该变量在函数外部并没有定义,导致程序无法识别该变量,进而报错。同样的问题也出现在函数 `decrypt()` 中。
为了修复这个问题,你需要将 `plaintext_entry` 定义为全局变量,这样它就可以被所有函数访问。你可以将 `plaintext_entry` 的定义放在 `root` 的创建之前,或者在函数 `encrypt()` 和 `decrypt()` 中声明 `plaintext_entry` 为全局变量。修改后的代码如下所示:
```python
from tkinter import *
from crypto.Cipher import DES
plaintext_entry = None # 将 plaintext_entry 定义为全局变量
def encrypt():
global plaintext_entry # 声明 plaintext_entry 为全局变量
key = bytes(key_entry.get(), 'utf-8')
cipher = DES.new(key, DES.MODE_ECB)
plaintext = bytes(plaintext_entry.get(), 'utf-8')
ciphertext = cipher.encrypt(plaintext)
ciphertext_entry.delete(0, END)
ciphertext_entry.insert(0, ciphertext.hex())
def decrypt():
global plaintext_entry # 声明 plaintext_entry 为全局变量
key = bytes(key_entry.get(), 'utf-8')
cipher = DES.new(key, DES.MODE_ECB)
ciphertext = bytes.fromhex(ciphertext_entry.get())
plaintext = cipher.decrypt(ciphertext)
plaintext_entry.delete(0, END)
plaintext_entry.insert(0, plaintext.decode('utf-8'))
root = Tk()
# 定义 plaintext_entry
plaintext_label = Label(root, text="Plaintext:")
plaintext_label.grid(row=0, column=0)
plaintext_entry = Entry(root)
plaintext_entry.grid(row=0, column=1)
# 其他代码保持不变
```
这样修改之后,程序就能够正确运行了。
阅读全文