Search code examples
pythontkintertkinter-label

why label doesnt work?Is it for 'for' loop?



The label in this application does not display the password once the generate button is clicked. I think it might be from the "for" loop. Any help would be appreciated.


from tkinter import *
from tkinter import ttk
import random
window = Tk()
window.resizable(False , False)
window.title('Password Generator')
window.geometry('400x200')

length = IntVar()
lbl = StringVar()
var1 = StringVar()

Alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
showpass = ttk.Label(window , textvariable = lbl).pack()

def randalp():

    for i in range(length):
        random.choice(Alphabet)

ttk.Label(window , text = 'Password Lentgh:').pack()
numchoosen = ttk.Combobox(window, width = 12 , textvariable = length)
numchoosen['values'] = (5,6,7,8,9,10)
numchoosen.pack()
numchoosen.current(2)
numchoosen.config(state = 'readonly')
rad1 = ttk.Checkbutton(window , text = 'Alphabet' , variable = var1).pack()

def btnclick():
    get1 = var1.get()
    if rad1 == '1':
            lbl.set(randalp)
            print(lbl)

btn = ttk.Button(window , text = 'Generate' , command = btnclick).pack()
window.mainloop()

Solution

  • Does this fix it for You:

    First You have to change Your randalp() function a bit:

    def randalp():
        string = list(Alphabet)
        random.shuffle(string)
        return string[:5]
    

    I used shuffle because it just shuffles a list in a random order, so taking the first 5 items from that list would be random.

    Also changed the btnclick() function:

    def btnclick():
        get1 = var1.get()
        if get1 == '1':
            lbl.set(randalp())
    

    so now it uses the returned value of randalp()

    Also You should fix a few formatting issues with Your code: suggestion: follow PEP 8 because it makes the code easier to read and don't use built-in function names (like len) as variable names; it is quite bad practice.