按下按钮时代码不会运行

时间:2018-03-28 09:02:03

标签: python python-3.x encryption tkinter cryptography

所以我一直在做我的课程,我正在尝试加密密码。但是,代码会在我开始初始化程序时运行,并且在按下指定按钮时不会运行。这就是我到目前为止所做的:

import tkinter as tk
from cryptography.fernet import Fernet

#validate function
def validateStylist(window):
    password = passwordEntry.get().encode("utf-8")
    cipher_text = cipher_suite.encrypt(password)
    plain_text = cipher_suite.decrypt(cipher_text)
    print(plain_text)

key = Fernet.generate_key()
cipher_suite = Fernet(key)

MEDIUM_FONT = ("Berlin Sans FB", 12)
LARGE_FONT = ("Berlin Sans FB", 16)

window = tk.Tk()

titleLabel = tk.Label(window, text="Register Stylist", font=LARGE_FONT, bg="#FFC0CB")
titleLabel.grid(columnspan = 4)

#Password
passwordLabel = tk.Label(window, text="Password:", font=MEDIUM_FONT, bg="#FFC0CB")
passwordLabel.grid(row=1,column=3)
passwordVar = tk.StringVar(window)
passwordEntry = tk.Entry(window, textvariable=passwordVar)
passwordEntry.grid(row=2,column=3)

finishButton = tk.Button(window, text="Finish",
                          command=validateStylist(window))
finishButton.grid(row=4, column=3, sticky="ew")


window.mainloop()

1 个答案:

答案 0 :(得分:1)

以下列方式使用lambda可以解决您的问题;它将确保按钮仅在按下时运行代码,而不是事先(当程序运行时)。

command=lambda: validateStylist(window)

因此,为清楚起见,您的新行将是:

finishButton = tk.Button(window, text="Finish",
                      command=lambda: validateStylist(window))