Cant get to update Label using a variable

Viewed 38

So i just made a password generator but everytime i generate a new one the label doesnt updates,it just adds a new password in the window keeping the previous ones

import random
import string
import time
from tkinter import *


def pass_generator():
    length = textBox.get()
    characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
    password = []
    display_pass = StringVar()

    while len(password) < int(length):
        password.append(random.choice(characters))
        display_pass.set("".join(password))

   print("This is your password: \n")
   print("".join(password))
   Label(window, textvariable=display_pass).pack()

# with open("passwords.txt", "a") as f:
#     date = time.strftime("%d/%m/%Y %H:%M:%S")
#     f.write(f"{date}: " + "".join(password) + "\n")


window = Tk()
window.geometry("500x150")
textBox = IntVar()
text = Label(window, text="Password length:").pack(side=LEFT)
length_entry = Entry(window, textvariable=textBox).pack(side=RIGHT)
button1 = Button(window, text="Generate", command=pass_generator).pack(side=BOTTOM)
window.mainloop()

I want to replace the current password with the new generated one but i cant get to do that

1 Answers

It is because you create new label for the new generated password. You need to create the result label once outside the function and update the result label inside the function:

import random
import string
from tkinter import *

def pass_generator():
    length = textBox.get()
    characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
    password = "".join(random.choice(characters) for _ in range(int(length)))
    # below is to generate password without duplicate characters
    #random.shuffle(characters)
    #password = "".join(characters[:int(length)])

    print("This is your password:", password)
    result.config(text=password) # show the password

window = Tk()
window.geometry("500x150")
textBox = IntVar()
Label(window, text="Password length:").pack(side=LEFT)
Entry(window, textvariable=textBox).pack(side=RIGHT)
Button(window, text="Generate", command=pass_generator).pack(side=BOTTOM)
# label for the generated password
result = Label(window)
result.pack()
window.mainloop()
Related