首页 > 解决方案 > 为什么我的 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应该发生的是,每次单击;时都会出现一系列新的随机字母、数字和标点符号。但是,当您单击它时,什么也没有发生。

标签: pythontkinter

解决方案


在这一行:

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调用函数(回调)。


推荐阅读