2

我正在尝试创建一个基本的电子邮件客户端来娱乐。我认为如果密码框显示随机字符会很有趣。我已经有一个创建随机字符的功能:

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

但问题是这只运行一次,然后程序无限期地重复该字符。

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

每次输入字符时,如何让 Entry 小部件重新运行该功能?

4

1 回答 1

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"
于 2013-04-20T05:31:56.047 回答