每次输入一个字符时,如何让 Tkinter 输入框重复一个功能? [英] How to have a Tkinter Entry box repeat a function each time a character is inputted?

查看:21
本文介绍了每次输入一个字符时,如何让 Tkinter 输入框重复一个功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了好玩,我正在尝试创建一个基本的电子邮件客户端.我认为如果密码框显示随机字符会很有趣.我已经有了一个创建随机字符的函数:

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)

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

推荐答案

不幸的是,Entry 小部件的 show 属性不能那样工作:就像你一样我注意到,它只是指定了一个单独的字符来显示,而不是输入的字符.

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.

要获得您想要的效果,您需要拦截 Entry 小部件上的按键,然后翻译它们.但是,您必须小心,只更改您真正想要的键,而保留其他键(特别是 Return、Delete、箭头键等).我们可以通过将回调绑定到 Entry 框上的所有按键事件来实现:

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)

其中 callback() 被定义为调用你的随机函数,如果它是一个 ascii 字母(这意味着数字未经修改通过),插入随机字符,然后返回特殊的 break 字符串常量,表示不再处理此事件):

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"

这篇关于每次输入一个字符时,如何让 Tkinter 输入框重复一个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆