输入验证作为类方法

时间:2018-04-18 07:35:45

标签: python class validation input tkinter

尝试将输入验证用于Toplevel窗口上的某些tkinter条目小部件,但我一直在用类定义所有内容(窗口/框架)。所以现在当我尝试注册验证功能时,我不太确定要注册谁,我尝试了类名,但这给了我一个名字(类名)没有定义'错误。我如何注册以下验证函数来在类中工作?我创建了一个Medical类的实例,以便打开Toplevel窗口,但这是另一个单独的类的不同方法...

class Medical(tk.Toplevel):
    def __init__(self, master, *args, **kwargs):
        tk.Toplevel.__init__(self, master, *args, **kwargs)
        self.master = master
        self.resizable(width=False, height=False)
        self.title('Medical Certificate Information')
        self.attributes('-topmost', True)
        self.geometry('230x230+580+280')
        self.grab_set()
        self.transient(master)
        self.duedate = tk.StringVar()
        self.age = tk.StringVar()

        frame1 = tk.Frame(self, bd=4, relief='ridge', width=230, height=230)
        frame1.place(anchor='nw')

        birthdate = tk.Label(self, text='Enter Birth Date(XX/XX/XXXX):', font='arial 10 bold')
        birthdate.place(anchor='nw', x=5, y=5)
        self.birthdate_entry = tk.Entry(self, font='arial 10 bold', width=10, relief='sunken', bd=2)
        self.birthdate_entry.place(anchor='nw', x=5, y=30)
        self.birthdate_entry.focus_set()

        agelabel = tk.Label(self, text = 'Age:', font='arial 10 bold')
        agelabel.place(anchor = 'nw', x= 130, y=30)
        ageinputlabel = tk.Label(self, font = 'arial 10 bold', textvariable = self.age)
        ageinputlabel.place(anchor = 'nw', x = 160, y = 30)

        medical = tk.Label(self, text='Medical Date(XX/XX/XXXX):', font='arial 10 bold')
        medical.place(anchor='nw', x=5, y=60)
        self.medical_entry = tk.Entry(self, font='arial 10 bold', width=10, relief='sunken', bd=2)
        self.medical_entry.place(anchor='nw',x=5, y=85)

        duedate = tk.Label(self, text='Medical Due Month:', font='arial 10 bold')
        duedate.place(anchor='nw', x=5, y=115)
        self.duedatelabel = tk.Label(self, font='arial 10 bold', width=10, relief='sunken', bd=2, textvariable=self.duedate)
        self.duedatelabel.place(anchor='nw', x=5, y=140)

        next = tk.Button(self, text='Next...', font='arial 10 bold', bd=2, bg='grey70', command=self.write)
        next.place(anchor='nw', x=170, y=195)

    def validate(self, inp, widget_name):
        if len(inp)<2:
            return True
        elif len(inp)==2:
            widget_name.insert('/')
            return True
        elif len(inp)<4:
            return True
        elif len(inp)==4:
            widget_name.insert('/')
            return True

    max1 = Medical.register(partial(validate, widget_name=self.birthdate_entry))
    max2 = Medical.register(partial(validate, widget_name=self.medical_entry))

    self.birthdate_entry.config(validate='key', validatecommand=(max1, '%P'))
    self.medical_entry.config(validate='key', validatecommand=(max2, '%P'))

感谢您的帮助。

0 个答案:

没有答案