How can I generate a new string using the same function? (tkinter, python)

Question:

I am creating a simple password generator, it should make a new one every time I press the button. How would I do that? Every time I do it, it prints/shows the same password. I think I understand why it’s not working the way I want it to but I don’t know how to fix it. Thank you.

from tkinter import *
import random
    
def password_generator():
    numbers = "1234567890"
    upper_case_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lower_case_letters = "abcdefghijklmnopqrstuvwxyz"
    special_chars = "!@#$%^&*()[];:"
    
    password_length = random.randint(9, 15)
    
    combo = numbers + upper_case_letters + lower_case_letters + special_chars
    
    password = "".join(random.sample(combo, password_length))
    
    return password
    
    
def printSomething():
    label = Label(window, text = password)
    label.pack() 

password = password_generator()
window = Tk()
    
window.geometry("400x250")
window.title("Password Generator")
window.config(background = "black")

button = Button(window, text = "Generate")
button.pack()
button.config(command = printSomething) 
button.config(font = ("", 50, "bold")) 
    
window.mainloop()
Asked By: Jasmit

||

Answers:

This line is running the function and returning a single generated password:

password = password_generator()

So the password is already generated before you run the user interface.

Instead, remove this line, and generate a new password each time you call the function printSomething(), i.e. the function should be

def printSomething():
    label = Label(window, text = password_generator())
    label.pack() 

Notice that I replaced password, which already called the function and generated a single password, with password_generator(), which calls the function each time printSomething() is called. This way, a new password is generated every time the user clicks the button.

Answered By: Adam Oppenheimer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.