'Run generator when button is clicked

I want to create a Button to generate a password with tkinter but when the script is running, the password is already generated and the button doesn't work.

Here is the button script:

import tkinter as tk
import string
from random import randint, choice

def generate(target):
    letter_min = 6
    letter_max = 15
    all_chr = string.ascii_letters + string.punctuation + string.digits
    password = "".join(choice(all_chr)for x in range(randint(letter_min, letter_max)))
    target.delete(0, tk.END)
    target.insert(0, password)

password_button = tk.Button(f2, text="Générer", font=("Arial", 20), bg=gris, fg='white', command=generate(password_entry))
password_button.pack(fill=tk.X)    


Solution 1:[1]

password_button = tk.Button(f2, text="Générer", font=("Arial", 20), bg=gris, fg='white', command=generate(password_entry))

The command argument of tkinter.Button's constructor takes a function, not the value returned by the function.


Replace

command=generate(password_entry)

with

command=lambda : generate(password_entry)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FLAK-ZOSO