用空字符串替换空格时条目验证失败

Entry validation fails when replacing spaces with empty strings

我不确定为什么在我最终替换字符串中的空格后验证停止工作。 对于我需要的大多数东西,验证工作正常。它只允许数字和最多 10 个,同时还允许退格并突出显示所有和退格。粘贴包含空格的值时,它也可以工作一次。

例如,如果我尝试将 12 34 粘贴到输入字段中,它将正确地将值更改为 1234,但在验证之后就停止工作了。

更新:

似乎在 entry.delete() 之后验证停止工作,但我仍然不确定如何更正此问题。我试图重新定义验证,但没有用。

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.vcmd = (self.register(self.validate), '%d', '%P', '%s')
        self.entry = tk.Entry(self, validate='key', validatecommand=self.vcmd)
        self.entry.pack()

    def validate(self, *a):
        b = a[1].replace(' ', '')
        if b.isdigit() and len(b) <= 10 or ((b == '' or b < a[2]) and a[0] == '0'):
            if ' ' in a[1]:
                x = a[1]
                x = x.replace(' ', '')
                self.entry.delete(0, 'end')
                self.entry.insert(0, x)
            return True

        else:
            return False

App().mainloop()

更新:

我设法通过删除输入字段并在插入新字符串后重新定义它及其验证来使其工作。但是这种接缝就像是错误的方法。

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.vcmd = (self.register(self.validate), '%d', '%P', '%s')
        self.entry = tk.Entry(self, validate='key', validatecommand=self.vcmd)
        self.entry.pack()

    def validate(self, *a):
        b = a[1].replace(' ', '')
        if b.isdigit() and len(b) <= 10 or ((b == '' or b < a[2]) and a[0] == '0'):
            if ' ' in a[1]:
                x = a[1]
                x = x.replace(' ', '')
                self.entry.destroy()
                self.entry = tk.Entry(self)
                self.entry.insert(0, x)
                self.entry.config(validate='key', validatecommand=self.vcmd)
                self.entry.pack()
            return True
        else:
            return False

App().mainloop()

I am not sure why validation stops working after I end up replacing spaces in a string. The validation works fine for most things I need.

它停止工作是因为它的设计就是这样工作的。如果您尝试从验证函数中修改数据,validate 选项会自动重置为 "none"。

官方 tcl/tk 文档是这样说的:

The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand.

如果您从验证函数中修改小部件,则需要重置 validate 选项。