Python Forum
[Tkinter] [SOLVED] Password generation UnboundLocalError exception - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] [SOLVED] Password generation UnboundLocalError exception (/thread-38707.html)



[SOLVED] Password generation UnboundLocalError exception - Milan - Nov-14-2022

Hello team,

I have the following code:

from tkinter import *
import random
import string

random_string = string.ascii_letters + string.digits + string.punctuation

root = Tk()

root.title('Password Generator')

root.geometry("450x300")


def generatePasswordButtonClicked():
    try:
        lenght = int(userInput.get())
    except UnboundLocalError:
        resultLabel.configure(text="Wrong input")
    except ValueError:
        resultLabel.configure(text="Wrong input")
    password = ''.join(random.sample(random_string, lenght))
    resultLabel.configure(text="Password: " + password)


def cancelButtonClicked():
    root.destroy()


generateButton = Button(root, text='Create Password',
                        command=generatePasswordButtonClicked)

generateButton.grid(row=0, column=0)

closeButton = Button(root, text='Close', command=cancelButtonClicked)

closeButton.config(bg='#9FD996')

closeButton.grid(row=1, column=0)

userInput = Entry(root, width=10)

userInput.grid(row=2, column=0)

resultLabel = Label(root, text="Password: ")

resultLabel.grid(row=3, column=0)

root.mainloop()
When I run it and insert a string or symbol to the resultLabel label, it spits on the terminal the following error:

Error:
UnboundLocalError: local variable 'lenght' referenced before assignment
Despite the except UnboundLocalError added. I also tried moving around the
lenght = int(userInput.get())
on line 16, which I thought it might be root cause. Wall

Any thoughts on how to work this out?

Thanks in advance.


RE: Password generation UnboundLocalError exception - Yoriz - Nov-14-2022

When userInput.get() returns a string that int cannot work with it raises a ValueError
Your try/except is capturing the ValueError the consequence of this it that lenght will not be defined.

if you add an else, the code in else only happens if the try part was successful.
   ...
    except ValueError:
        resultLabel.configure(text="Wrong input")
    else:
        password = ''.join(random.sample(random_string, lenght))
        resultLabel.configure(text="Password: " + password)



RE: Password generation UnboundLocalError exception - Milan - Nov-14-2022

Works like a charm. Thanks a million.
(Nov-14-2022, 06:08 PM)Yoriz Wrote: When userInput.get() returns a string that int cannot work with it raises a ValueError
Your try/except is capturing the ValueError the consequence of this it that lenght will not be defined.

if you add an else, the code in else only happens if the try part was successful.
   ...
    except ValueError:
        resultLabel.configure(text="Wrong input")
    else:
        password = ''.join(random.sample(random_string, lenght))
        resultLabel.configure(text="Password: " + password)



RE: [SOLVED] Password generation UnboundLocalError exception - menator01 - Nov-14-2022

Here is another example of a password generator

# Do the imports
from random import sample
import string

import tkinter as tk

# Combine upper and lower case letters with digits and special characters
# into a string
characters = string.ascii_letters + string.digits + '!@#$&*+'

# Define the function
def password_generator(passwd):
    # Return a joined string with 10 sample charcters
    # return ''.join(sample(characters, 10))
    passwd['text'] = ''.join(sample(characters, 10))

root = tk.Tk()
label = tk.Label(root, text='Password Generater', bg='steelblue', fg='white')
label['font'] = ('serif', 18, 'bold')
label.pack()

passwd = tk.Label(root, bg='antiquewhite', relief='ridge')
passwd['font'] = ('serif', 14, 'normal')
passwd.pack(expand=True, fill='x', pady=4)

button = tk.Button(root, text='Generate Password', command=lambda: password_generator(passwd))
button['font'] = ('comic sans ms', 12, 'bold')
button.pack(expand=True, fill='x')
root.mainloop()