python - tkinter:当输入小部件已满时将焦点移至下一个小部件,而不会丢失击键

标签 python python-3.x tkinter focus tkinter-entry

这是我在这里提出的第一个问题,如果我做错了,很抱歉。

我正在创建一个入口类,它将验证输入的长度,然后关注下一个小部件。下面的代码执行此操作,但它会在所需的长度之后触发按键上的焦点更改,这会导致我们丢失该按键

示例:如果您在第一个输入框中输入 123456789,则最终结果将在输入框 1 中为 1234,在输入框 2 中为 6789

import tkinter as tk

class ValidateEntry(tk.Frame):

    def __init__(self, parent, width=20, txt=None): 
        tk.Frame.__init__(self, parent)
        self.width = width
        vcmd = (self.register(self.validate), '%i', '%S', '%d', '%P')
        self.entry = tk.Entry(self, width=self.width, validate='key', vcmd=vcmd)
        if txt is not None:
            self.entry.insert('end', txt)
        self.entry.pack()

    def validate(self, i, S, d, P):# i = index, S = insert character, d = action, P = entry value
        if len(P)-1 == self.width and d != 0:
            self.entry.tk_focusNext().focus()
            return False
        return True

root = tk.Tk()
entry1 = ValidateEntry(root, width=4)
entry2 = tk.Entry(root, width=8)
entry1.pack()
entry2.pack()
root.mainloop()

我无法找到一种方法来改变焦点并保留上面示例中的第五次按键

最佳答案

在第四次按键时,您想要接受该键(因此返回 true)并更改焦点。所以只需将验证函数更改为:

def validate(self, i, S, d, P):# i = index, S = insert character, d = action, P = entry value
    if len(P) == self.width and d != 0:
        self.entry.tk_focusNext().focus()
    return True

关于python - tkinter:当输入小部件已满时将焦点移至下一个小部件,而不会丢失击键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60104170/

相关文章:

python - 将图像转换为位图

python - a def 在函数中的用法是什么?

python - 如何使用 PYTHON 的 mysql-connector 将 MySQL 数据库导出为 json?

python-3.x - Python。自然语言处理。预处理文本

python - 类型错误 : unorderable types: IntVar() > int()

python - 当套接字循环发生时,Tkinter 无法工作

python - 如何从输入中搜索列表中的特定单词

python - AWS IAM : change Access Key Id the from root to IAM

python - python 中的 'too many values to unpack' 错误

python-2.7 - StringVar 实例没有属性 'delete'