Question

I am trying to make a random "password" generator that will display a random string of characters in a tkinter entry widget. The problem is that everytime the button is clicked it generates a new entry widget instead of updating the current one. I tried moving and tweaking the "entry = g.en(text=word)" string but when I do that the button click doesn't produce anything in the box. I've been working at this for a while and I am yet to come up with a solution.

import random
from swampy.Gui import *
from Tkinter import *
import string

#----------Defs----------
def genpass():
    word = ''
    for i in range(10):
        word += random.choice(string.ascii_letters + string.punctuation + string.digits)
    entry = g.en(text=word)

#----------Main----------
g = Gui()
g.title('Password Helper')
label = g.la(text="Welcome to Password Helper! \n \n Choose from the options below to continue. \n")

button = g.bu(text='Generate a New Password', command=genpass)

g.mainloop()
Was it helpful?

Solution

since you do this:

entry = g.en(text=word)

inside the function and the button calls the function each time it is pressed, You are going to get a new item each buttonpress.

that way the gui waits for the button to be pushed to run the command.

Secondly I think you will have a lot easier time with this if you remove the entry creation from the function. Rather I would suggest that you define the entry before calling the function, and have the function get/change the value (setting up with classes for a GUI is a big help). That way you won't be always creating a new entry box each button click.

Try this:

from Tkinter import *
import random

class MYGUI:
    def __init__(self):

        root=Tk()
        root.title('Password Helper')
        label = Label(root, text="Welcome to Password Helper! \n \n Choose from the options below to continue. \n")
        self.button=Button(root, text='Generate a New Password', command=lambda: self.genpass())
        self.word=Label(root)

        label.pack()
        self.button.pack()
        self.word.pack()
        mainloop()

    genpass(self):
        word = ''
        for i in range(10):
            word += random.choice(string.ascii_letters + string.punctuation + string.digits)
        self.word['text']=word

if __name__ == '__main__':
    MYGUI()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top