gpt4 book ai didi

python - 使用 tkinter 减少输入字母不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 04:30:01 25 4
gpt4 key购买 nike

我程序中的数字输入小部件正常工作,最多只允许输入 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

关于python - 使用 tkinter 减少输入字母不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52845073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com