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

时间:2017-02-19 21:12:37

标签: python validation tkinter field tkinter-entry

我一直在尝试在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()

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

1 个答案:

答案 0 :(得分:0)

要对浮点数进行验证,只需在允许编辑(%P)时为验证命令指定值即可。尝试将其转换为浮点数,如果失败则返回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

有关条目小部件验证的详细信息,请参阅以下答案:https://stackoverflow.com/a/4140988/7432