Python Forum
[Tkinter] [SOLVED] Password generation UnboundLocalError exception
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] [SOLVED] Password generation UnboundLocalError exception
#1
Brick 
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.
Reply
#2
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)
Reply
#3
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)
Reply
#4
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 + '[email protected]#$&*+'

# 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()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Is it possible to automate button generation in tkinter? FirePepi 3 1,798 Apr-10-2020, 12:14 PM
Last Post: Riddle
  [WxPython] Issues with Exe generation and Packaging dependencies Ravikumar 1 2,194 Nov-23-2017, 12:53 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020