所以我正在制作这个文件加密器和解密器,现在我正试图使用Tkinter GUI将其制作成一个应用程序.收到此错误



很久以前,我看了一个关于如何用密钥/密码加密文件(任何类型)的教程最初的代码只是在终端中进行处理,但我想把它变成一个使用tkinter作为GUI的应用程序,我遇到了一个问题,我的小脑袋无法解决

原始视频:https://www.youtube.com/watch?v=HHlInKhVz3s

这是我得到的错误:TypeError: Encrypt() missing 2 required positional arguments: 'WhichFile' and 'KeyInput'

这是我的代码:

from tkinter.filedialog import askopenfilename
import time

root = Tk()
root.title=("Tkinter Calculator")
root.geometry("500x500")

#title
WindowTitle = Label(root, text="Choose Action", font=("Arial", 15))
WindowTitle.place(x=250, y=10,anchor="center")
### The functions


#Encrypt
def Encrypt(WhichFile, KeyInput):
file = open(WhichFile, "rb")
data = file.read()
file.close()

data = bytearray(data)
for index, value in enumerate(data):
data[index] = value ^ KeyInput


file = open("CC-" + WhichFile, "wb")
file.write(data)
file.close()



#Decrypt
def Decrypt(WhichFile, KeyInput):
file = open(WhichFile, "rb")
data = file.read()
file.close()

data = bytearray(data)
for index, value in enumerate(data):
data[index] = value ^ KeyInput


file = open(WhichFile, "wb")
file.write(data)
file.close()




#Step1 - Write the name of the file(Needs to be in the same folder(Also include ext.))
WhichFile = Entry(root, width = 20)
WhichFile.place(x=100, y=150)
WhichFile.insert(0, "Enter File name with extension")
#Step2 - Ask for a key/password
KeyInput = Entry(root, width = 20)
KeyInput.place(x=100, y=250)
KeyInput.insert(0, "Enter a key: ")
#Button for encrypt
Encryptbtn = Button(root, text="Encrypt", highlightbackground='#3E4149', command=Encrypt)
Encryptbtn.place(x=100, y=350)


#Button for decrypt
Decryptbtn = Button(root, text="Decrypt", highlightbackground='#3E4149', command=Decrypt)
Decryptbtn.place(x=200, y=350)

root.mainloop()

所以错误发生在这一行:

Encryptbtn = Button(root, text="Encrypt", highlightbackground='#3E4149', command=Encrypt)

将带有参数的函数传递给Button的";命令">

您必须将参数传递给函数Encrypt(),该函数需要参数";WhichFile";以及";键输入";。您可以使用lambda关键字在Button声明中传递参数:

Button(root, text="Encrypt", highlightbackground='#3E4149', command=lambda:Encrypt(file,input))

它将取"0"的值;文件";以及";输入";只是当你点击按钮时,记住它,因为有时它并不是你真正想要的(例如Python Tkinter按钮回调)。如果您希望参数是";记住";就像他们在创建按钮时一样,使用currying(什么是咖喱,更多关于";λ)。


因此,首先必须将参数传递给该函数。正如我所看到的,你有点不理解它是如何工作的,因为你试图在函数的声明中使用参数,就像它们是某个事物的全局变量一样(def Encrypt(WhichFile, KeyInput),然后作为"赋值"WhichFile = Entry(...)),但它不是这样工作的,传递给函数的参数是在函数的调用中指定的,例如foo(argument1,argument2),而不是在定义它的时候。

正在从条目中获取文本:

您必须知道,WhichFile = Entry(root, width = 20)不是将Entry的值分配给WhichFile变量,而是将Entry本身(使用print(WhichFile)进行检查)。我建议将该变量的名称更改为例如"0";user_input_file"或某事。如果要在条目中键入文本,请使用user_input_file.get()。与KeyInput Entry完全相同。

接下来,您必须创建一个指向该值的变量(python变量是指针),并以我之前提到的方式(使用lambda:)在该函数中分配它。只需将其写为全局变量,例如:

WhichFile = user_input_file.get()
KeyInput = user_input_key.get()

当然,在声明user_input_file和user_input_key之后。

我认为这会解决你的问题,请随意询问更多。

最新更新