我程序中的数字输入小部件正常工作,最多只允许输入 3 个数字,而我试图在不同的输入小部件中做同样的事情,但对于字符,限制不起作用,我没有知道为什么。由于您使用的是字母,您是否必须以不同的方式使用它?
这是我的代码:
def only_letters_max_86(action, char):
if action == "1":
# a character is inserted (deletion is 0) allow the insertion
# only if the inserted character char is a letter
return char.isalpha() and len(char) <= 86
else:
# allow deletion
return True
def only_numbers_max_3(action, new_text):
if action == "1":
return new_text.isdigit() and len(new_text) <= 3
else:
return True
def main():
validate_letter = window.register(only_letters_max_86)
validate_nb = window.register(only_numbers_max_3)
label = Label(window, width = 30, background = 'lightgreen', text='enter temperature, only numbers')
label.grid(row=0, column=0)
entry_tempp = Entry(window, width = 30, validate="key", validatecommand=(validate_nb, '%d', '%P'))
entry_tempp.grid(row = 0, column = 1)
#create another label and entry object for location
label_numb = Label(window, width = 30, background = 'lightgreen', text='enter location, only letters')
label_numb.grid(row=1, column=0)
entry_locations = Entry(window, width = 30, validate="key", validatecommand=(validate_letter, '%d', '%S', '%v'))
entry_locations.grid(row = 1, column = 1)
请您参考如下方法:
这一行: entry_locations = Entry(window, width = 30, validate="key", validatecommand=(validate_letter, '%d', '%S', '%v'))
您正在将 '%S' 传递给您的 validate_letter 函数,查看文档意味着:
'%S': If the call was due to an insertion or deletion, this argument will be the text being inserted or deleted.
所以我的猜测是 only_letters_max_86(action, char) 中的 char 只获取正在插入的字符,该字符的长度始终为 1,导致您的检查失败。尝试将 %S 更改为 %P,这会为您提供:
'%P': The value that the text will have if the change is allowed.
文档链接:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html
