How to have a Tkinter input field, repeat a function every time a character is entered?

I am trying to create a basic email client for fun. I thought it would be interesting if the password field would show random characters. I already have a function to create 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 problem is that this is executed only once, and then the program repeats this character indefinitely.

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

How do I get an Entry widget to re-run a function every time a character is entered?

+2
source share
1 answer

Unfortunately, the show attribute of the Entry widget does not work this way: as you noticed, it simply indicates one character to display instead of what was printed.

To get the desired effect, you need to intercept keystrokes on the Entry widget and then translate them. However, you should be careful not only to mutate the keys that you really want and leave others (in particular, β€œReturn”, β€œDelete”, arrow keys, etc.). We can do this by attaching a callback to all keypress events in the input field:

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

where callback() is defined to call your random function, if it is the letter ascii (which means the numbers go through unmodified ones), insert a random character, and then return the special string constant break to indicate that processing no longer needs this event happen):

 def callback(event): if event.char in string.ascii_letters: event.widget.insert(END, random_char()) return "break" 
+1
source

All Articles