如何让验证在 tkinter 输入字段中工作?

How to get validation to work in tkinter entry fields?

我一直在尝试在 tkinter 的输入字段中实施验证,因此您只能输入整数:这是我现在拥有的代码:

import tkinter as tk

class window2:
  def __init__(self, master):
    self.panel2 = tk.Frame(master)
    self.panel2.grid()
    self.button2 = tk.Button(self.panel2, text = "Quit", command = self.panel2.quit)
    self.button2.grid()

    self.entryfields()

def entryfields(self):

    vcmd = (self.register(self.validate),
            '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
    self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
    self.text1.grid()
    self.text1.focus()

def validate(self, action, index, value_if_allowed,
    prior_value, text, validation_type, trigger_type, widget_name):
    if(action=='1'):
        if text in '0123456789.-+':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
    else:
        return True

if __name__ == "__main__":

root1 = tk.Tk()
window2(root1)
root1.mainloop()

部分代码也来自该论坛。我认为这是我遗漏的继承问题。

要对浮点数进行验证,如果允许编辑 (%P),您只需为验证命令赋予值。尝试将其转换为浮点数,如果失败则 return False 如果成功则 True

例如:

class window2:
    ...    
    def entryfields(self):
        vcmd = (self.panel2.register(self.validate), '%P')
        self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
        self.text1.grid()
        self.text1.focus()

    def validate(self, value_if_allowed):
        if value_if_allowed == "":
            # allow null entries so the user can delete everything
            # before entering a value if they wish. 
            return True

        try:
            float(value_if_allowed)
            return True

        except ValueError:
            self.panel2.bell()
            return False

有关条目小部件验证的更多信息,请参阅此答案: