每次 Entry 小部件的值更改时调用 Command 函数

Call Command function every time Entry widget's value changes

我想在每次 Entry 小部件中输入的值发生变化时调用 check_value 函数,但它只是第一次调用。

class table(tk.frame)
    ....
    ....#some functions
    def enterdata(self):
        ....
        ....
        for i in range(1,no_of_params):
            cell=work_sheet.cell(i,0)
            table.param_l.append(cell.value)
            var=StringVar()
            Button(middleframe,text=cell.value,width=40,height=2,command=lambda i=i :self.info(i)).grid(row=i+3,column=0)
            entry=Entry(middleframe,validate='focusout',validatecommand=lambda i=i:self.checkvalue(middleframe,i-1),\
                   textvariable=var,bd=5,width=30).grid(row=i+3,column=1)
            table.val.append(var)
            Label(middleframe,text="Enter value",width=15,height=2,bd=5).grid(row=i+3,column=2)

    def checkvalue(self,middleframe,r):
        if r==0:
            print table.val[r].get()    
            if "2" in table.val[r].get():
                        Label(middleframe,text="SUCCESS",fg="Dark Green",width=15,height=2,bd=5,\
                            font("Helvetica",11,"bold")).grid(row=r+4,column=2)
            else:
                        Label(middleframe,text="ERROR",fg="Dark Red",width=15,height=2,bd=5,\
                            font=("Helvetica",11,"bold")).grid(row=r+4,column=2)
        ......#similar checks for other values of 'r'

函数 必须 return TrueFalse。如果没有,验证将自动关闭。此外,您不能从该过程中更改条目小部件的值。你没有展示你的全部代码,所以我不知道你是不是这样做的。

此外,同时使用validatecommandtextvariable时需要小心。只要你只使用 var 来获取值而不是设置它,你应该没问题。

来自 the official tk documentation(构建 Tkinter 的基础):

In general, the textVariable and validateCommand can be dangerous to mix. Any problems have been overcome so that using the validateCommand will not interfere with the traditional behavior of the entry widget. Using the textVariable for read-only purposes will never cause problems. The danger comes when you try set the textVariable to something that the validateCommand would not accept, which causes validate to become none (the invalidCommand will not be triggered). The same happens when an error occurs evaluating the validateCommand.

Primarily, an error will occur when the validateCommand or invalidCommand encounters an error in its script while evaluating or validateCommand does not return a valid Tcl boolean value. The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated. If you wish to edit the entry widget (for example set it to {}) during validation and still have the validate option set, you should include the command