英文:
Validate command function for Ctk.Entry that does not accept input if the first character is a number?
问题
我正在尝试为我的 Ctk.Entry 小部件创建一个验证命令函数,该函数不允许用户输入以数字开头的内容。
例如,可以是:
- abcd ef
- abcd123 ab1
- a1b2c3 1c
但不能是:
- 1bcd
- 1 abc
- 123abc
- 123 abc
我已成功为另一个小部件创建了一个允许仅输入数字的“回调”函数,它运行良好,但我在上述函数中遇到了问题。以下是代码:
def callback1(P):
'''执行输入验证。
仅允许不以数字开头的输入
'''
if P.strip() == "":
return True
elif P[0].isdigit() == False:
return True
在这里,它被注册到小部件中(以防万一):
vcmd1 = (dashboard.register(callback1), "%P")
提前谢谢。
英文:
I am trying to create a validate command function for my Ctk.Entry widget, that does not allow the user to enter an input if the input starts with a number.
For example, can be:
- abcd ef
- abcd123 ab1
- a1b2c3 1c
but can NOT be:
- 1bcd
- 1 abc
- 123abc
- 123 abc
I have succesfully created a 'callback' function for another widget that allows the input to be a number only, works fine, but i am having issues with the function mentioned above. See for code
def callback1(P):
'''Perform input validation.
Allow only if does not start with number
'''
if P.strip() == "":
return True
elif P[0].isdigit() ==False:
return True
Here it is registered to the widget(just in case):
vcmd1 = (dashboard.register(callback1),"%P")
Thank you in advance
答案1
得分: 1
通过@Bryan Oakley的帮助,我找到了解决方法。
首先,在elif
语句内部不需要进行索引,因为该函数会检查完整的输入(如果输入是数字)。显然,如果以字母开头,输入就不会是数字。
其次,为了解决擦除输入并重新输入的问题,我在函数末尾留下了return True
,以便它继续运行并检查输入是否为isdigit()
。代码如下:
def callback1(P):
'''执行输入验证。
只允许不以数字开头的输入
'''
if P.strip() == "":
return True
elif P.isdigit():
dashboard.bell()
return False
return True # 使函数始终运行
英文:
With @Bryan Oakley 's help. I figured it out.
First, no need for the indexing inside the elif
statement, since the function checks for the full input (if the input is a number). And clearly the input will not be a number if started with a letter.
Second, to solve the issue of errasing the input and entering it again, I leave a return True
at the end of the function so that it keeps running and cheking if input isdigit()
. It looks like this.
def callback1(P):
'''Perform input validation.
Allow only if does not start with number
'''
if P.strip() == "":
return True
elif P.isdigit():
dashboard.bell()
return False
return True #so that the function always runs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论