Python Tkinter项目故障:无法获取输入并实现加密输出
修复Tkinter加密项目的输入获取与输出显示问题
你的代码存在几个关键问题导致无法正常运行,以下是问题分析和修正方案:
问题点
- 输入获取错误:
cuadroinput.get缺少括号,这会返回方法对象而非输入框的实际文本,正确写法是cuadroinput.get()。 - 加密参数错误:因为输入获取错误,
mensaje是方法对象,调用encode()会触发类型错误,修正输入获取后才能正确传递字符串进行加密。 - 输出更新错误:输出框绑定了
StringVar变量texto,应该用texto.set()来更新内容,而不是cuadroutput.config(Text=...);另外Fernet加密结果是字节类型,必须转成字符串才能存入StringVar。
修正后的完整代码
from tkinter import * from cryptography.fernet import Fernet raiz = Tk() raiz.title("Codec") raiz.resizable(False, False) raiz.config(bg="dark green") texto = StringVar() frame1 = Frame() frame1.pack() frame1.config(bg="dark green") frame1.config(width=650, height=400) prompt = Label(text="Coloque el texto a encriptar", fg="black", font="Bold", bg="dark green") prompt.place(x=230, y=80) def Encriptador(): # 正确获取输入框文本 mensaje = cuadroinput.get() if not mensaje: return # 空输入不处理 key = Fernet.generate_key() cifrar = Fernet(key) # 对字符串进行编码后加密 mensaje_cifrado = cifrar.encrypt(mensaje.encode()) # 将字节类型的加密结果转成字符串,更新到输出框的StringVar texto.set(mensaje_cifrado.decode()) cuadroinput = Entry(frame1, width=40) cuadroinput.place(x=200, y=120) cuadroutput = Entry(frame1, width=70, textvariable=texto) cuadroutput.place(x=100, y=300) boton = Button(raiz, text="Encriptar", command=Encriptador) boton.place(x=305, y=170) raiz.mainloop()
额外提示
每次点击加密按钮都会生成新的密钥,如果你需要解密加密后的内容,需要保存对应的密钥。可以添加一个标签或输入框来显示生成的密钥,方便后续解密使用。
内容的提问来源于stack exchange,提问作者rick
相关产品推荐
相关产品推荐

