What is the value of 4 when submitting a show argument callback to the Tkinter input field?

Question

Why is my random ascii character select function output four, and what is the meaning of the number 4 in this context? Why am I not getting an error message?

Remember that the question is not about how to solve the problem, it is the question of why this number was displayed.

Background and code

I am trying to create a primary email client. I thought it would be great for my password window to display random characters instead of the obvious *. So, I created a function that chose the random letter ascii.

import random import string def random_char(): char_select = random.randrange(52) char_choice = string.ascii_letters[char_select] return char_choice 

When I run this in an interactive terminal, it spits out a random letter. But when I launch it through my widget

 self.Password = Entry (self, show = lambda: random_char()) 

A bunch of four meet me.

Additional loan

If you have time, please visit my related question, How do I have a Tkinter input field repeat a function every time a character is entered?

+4
source share
1 answer

The show parameter takes a value, not a callback. Tkinter takes your callback object and tries to convert it to a string, and this is what you get when you type in the input field.

Instead, you can reconfigure your entry after input using the binding:

 def key(event): entry.configure(show = random_char()) entry = tk.Entry (self) entry.pack() entry.bind("<Key>", key) 

EDIT

Brian Oakley is right because it will change all characters to the same random character that you type. Displaying different random characters as you type is not the way you should use the Entry widget. You can try something like:

 def key(event): global real_password global garbage current_len = len(v.get()) if event.char and event.char in string.ascii_letters: real_password += event.char garbage += random_char() garbage = garbage[:current_len] v.set(garbage) v = tk.StringVar() real_password = "" garbage = "" entry = tk.Entry (self, textvariable = v) entry.pack() entry.bind("<KeyRelease>", key) 

Of course, there are many restrictions, the last character entered changes when the key is not released when it is pressed, so you need to type fast :), there is no control over the cursor keys, etc. But in any case, it was fun.

+1
source

All Articles