python - 为什么我的 tkinter 回调不返回密码?
问题描述
import string
from random import randint, choice
from tkinter import *
def generate_password():
password_min = 6
password_max = 12
all_chars = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(all_chars) for x in range(randint(password_min, password_max)))
password_input.delete(0, END)
password_input.insert(0, password)
window = Tk()
window.title("Henerateur de mot de passe")
window.geometry("720x480")
window.config(background='#4065A4')
frame = Frame(window, bg='#4065A4')
width = 300
height = 300
image = PhotoImage(file="password.png").zoom(35).subsample(32)
canvas = Canvas(frame, width=width, height=height, bg='#4065A4', bd=0, highlightthickness=0)
canvas.create_image(width / 2, height / 2, image=image)
canvas.grid(row=0, column=0, sticky=W)
right_frame = Frame(frame, bg='#4065A4')
label_title = Label(right_frame, text="Mot de passe", font=("Helvetica", 30), bg='#4065A4', fg="white")
label_title.pack()
password_input = Entry(right_frame, text="Mot de passe", font=("Helvetica", 30), bg='#4065A4', fg="white")
password_input.pack()
generate_password_button = Button(right_frame, text="Generer", font=("Helvetica", 30), bg='#4065A4', fg="#4065A4", command=generate_password())
generate_password_button.pack(fill=X)
right_frame.grid(row=0, column=1, sticky=W)
frame.pack(expand=YES)
window.mainloop()
generate_password_button
应该发生的是,每次单击;时都会出现一系列新的随机字母、数字和标点符号。但是,当您单击它时,什么也没有发生。
解决方案
在这一行:
generate_password_button = Button(right_frame, text="Generer",
font=("Helvetica", 30), bg='#4065A4',
fg="#4065A4", command=generate_password())
您指定generate_password()
为按下按钮时要执行的命令。这样做的效果是使用返回值generate_password()
作为要执行的命令,None
因为它没有显式返回任何内容,也不会发生任何事情。
相反,您想传递函数本身,而不调用它,即:
generate_password_button = Button(right_frame, text="Generer",
font=("Helvetica", 30), bg='#4065A4',
fg="#4065A4", command=generate_password)
现在,当您按下按钮时,将generate_password
调用函数(回调)。
推荐阅读
- java - 使用 Java 将 GeoJSON 坐标中的 Lat 和 Long 值分别提取为所需的格式
- javascript - 如果任何依赖项在路径中有“src”,则开玩笑“找不到模块”
- linux - 如何将 automake 文件写入递归构建子目录?
- swift - 对 Swift 中可以和数组或单个元素进行解码的 JSON 数据很热门?
- r - 在调用函数时,可以采取哪些额外的预防措施来防止不必要的引导到 if 语句中?
- php - array_push() 不会将新数组推入前一个数组并创建新索引
- android - 解析 json 时 Retrofit 和 moshi 出错
- java - Java 毕业计算器。为什么我会收到此错误?
- java - 如何分解 ArrayList
通过搜索给定字符并创建新的 ArrayList? - python - 如何在 PySpark 中使用 StructType 将浮点数转换为 IntegerType?