tkinter文本输入验证

2024-05-15 23:09:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python/tkInter验证文本输入

def validate_text():
    return False

text = Entry(textframe, validate="focusout", validatecommand=validate_text)

其中validate_text是函数-我尝试过总是返回False和True,结果没有任何差别。。?函数中是否有一组参数需要包含

编辑-从无更改为焦点输出…仍不工作


Tags: 函数text文本falsetrue编辑参数return
3条回答

我想你唯一缺少的就是一个invalidcommand (or invcmd)。如果validatecommand(或vcmd)返回false,您希望它做什么?根据Tk手册(见下文),如果vcmd返回False且validate设置为none,则调用invcmd。invcmd的典型命令是Tkinter.bell,它发出叮当声。还要注意的是,vcmd和invcmd非常敏感,如果遇到异常、小部件在vcmd或invcmd函数中发生了任何更改或vcmd未返回有效的Tcl布尔值,则会将validate变为“none”。尤其是textvariable因引起问题而臭名昭著,而且a section in Entry called valdation专门处理这个问题

以下是Tk命令条目的相关部分(与Spinbox相同)。有关更多参考资料,请参见下文

Command-Line Name: -validatecommand or -vcmd
Database Name: validateCommand
Database Class: ValidateCommand
Specifies a script to eval when you want to validate the input into the entry widget. Setting it to {} disables this feature (the default). This command must return a valid Tcl boolean value. If it returns 0 (or the valid Tcl boolean equivalent) then it means you reject the new edition and it will not occur and the invalidCommand will be evaluated if it is set. If it returns 1, then the new edition occurs. See Validation below for more information.

Command-Line Name: -invalidcommand or -invcmd
Database Name: invalidCommand
Database Class: InvalidCommand
Specifies a script to eval when validateCommand returns 0. Setting it to {} disables this feature (the default). The best use of this option is to set it to bell. See Validation below for more information.

更多参考资料,请查看this SO answerTk commandsepydoc-Tkinter

这个问题有很多重复的地方。 Python tkInter Entry fun
Restricting the value in Tkinter Entry widget

您应该注册验证函数

def validate_text():
    return False

textframe.register(validate_text)
text = Entry(textframe, validate="focusout", validatecommand=validate_text)

focusout意味着只有当您从entrywidget中取出焦点时,才会调用validatecommand

您可以在键入时尝试使用“key”进行验证

Tcl手册:
验证的工作方式是将validateCommand选项设置为脚本,该脚本将根据validate选项进行评估,如下所示:


  • 违约这意味着不会进行验证

  • 焦点
    当条目接收或失去焦点时,将调用validateCommand

  • 聚焦于
    当条目收到焦点时,将调用validateCommand

  • 聚焦输出
    当条目失去焦点时,将调用validateCommand


  • 编辑条目时将调用validateCommand

  • 全部
    将为所有上述条件调用validateCommand

相关问题 更多 >