2

I am trying to create an basic email client for fun. I thought that it would be interesting if the password box would show random characters. I already have a function for creating random characters:

import string
import random



def random_char():

    ascii = string.ascii_letters
    total = len(string.ascii_letters)
    char_select = random.randrange(total)

    char_choice = char_set[char_select]

    return char_choice

but the issue is that this is only run once, and then the program repeats that character indefinitely.

    self.Password = Entry (self, show = lambda: random_char())
    self.Password.grid(row = 1, column = 1)

How would I get the Entry widget to re-run the function each time a character is entered?

xxmbabanexx
  • 8,256
  • 16
  • 40
  • 60

1 Answers1

1

Unfortunately, the show attribute of the Entry widget doesn't work that way: as you've noticed, it simply specifies a single character to show instead of what characters were typed.

To get the effect you want, you'll need to intercept key presses on the Entry widget, and translate them, then. You have to be careful, though, to only mutate keys you really want, and leave others (notably, Return, Delete, arrow keys, etc). We can do this by binding a callback to all key press events on the Entry box:

self.Password.bind("<Key>", callback)

where callback() is defined to call your random function if it's an ascii letter (which means numbers pass through unmodified), insert the random character, and then return the special break string constant to indicate that no more processing of this event is to happen):

def callback(event):
    if event.char in string.ascii_letters:
        event.widget.insert(END, random_char())
        return "break"
ckhan
  • 4,771
  • 24
  • 26