JSmith JSmith - 4 months ago 43
Python Question

Python Tkinter label refresh

I'm trying to build a gui that creates a password and i've got as far as generating the password and making it appear in a label. However when the button is clicked multiple times it appears the old password doesnt dissapear, it just overlays on top. I'm also getting an error that i cant seem to rectify, although it doesnt seem to affect the gui.

The code so far is:

from tkinter import *
import random

myGui = Tk()
myGui.geometry('300x200+700+250')
myGui.title('Password Generator')

def passwordgen():
password = ''

for i in range(8):
##----runs the for loop 8 times
if (i == 0) or (i == 4):
password = password + chr(random.randint(97, 122))

if (i == 1) or (i == 5):
password = password + chr(random.randint(65, 90))

if (i == 2) or (i == 6):
password = password + chr(random.randint(48, 57))

if (i == 3) or (i == 7):
password = password + chr(random.randint(33, 47))

passLabel = Label(myGui, text=password)
passLabel.grid(row=0, column=1, sticky=E)

genPassBtn = Button(myGui, text="Generate Password", command=passwordgen)
genPassBtn.bind("<Button-1>", passwordgen)
genPassBtn.grid(row=0, column=0, sticky=W)

myGui.mainloop()


The error i receive is:

return self.func(*args)
TypeError: passwordgen() takes 0 positional arguments but 1 was given


The outcome i am hoping to achieve is to create a gui that generates a password, generates a hash value for generated password, checks the password strength, loads the generated hash to a text file and then can verify the password against stored hashes.

Answer

Try this example.

from tkinter import *
import random

myGui = Tk()
myGui.geometry('300x200+700+250')
myGui.title('Password Generator')

def passwordgen():
    password = ''

    for i in range(8):
        ##----runs the for loop 8 times
        if (i == 0) or (i == 4):
            password = password + chr(random.randint(97, 122))

        if (i == 1) or (i == 5):
            password = password + chr(random.randint(65, 90))

        if (i == 2) or (i == 6):
            password = password + chr(random.randint(48, 57))

        if (i == 3) or (i == 7):
            password = password + chr(random.randint(33, 47))

    strPassword.set(password)

genPassBtn = Button(myGui, text="Generate Password", command=passwordgen)
strPassword = StringVar()
lblPassword = Label(myGui, textvariable=strPassword)
lblPassword.grid(row=0,column=1, sticky=W)
genPassBtn.grid(row=0, column=0, sticky=W)

myGui.mainloop()

Here's what I've done

  1. Rather than creating a new label each time, I change the text of a label using the StringVar called strPassword.
  2. You don't need to bind a button to a click to call a function, using Button(... , command=myFunction) does this already.
Comments